But strings can be used for more complex operation for creating even more complex and flexible application. Let’s see a basic example:
In the above example, have used strings to create a popup message to the users. And probably the popup message uses a string for containing the text message.
We will learn more about function, alert, prompt etc. in details in the subsequent chapters.
var MyString = "This is a string!"; // double qouts string // or var MyString = 'This is a string!'; // single quots string
Yes, you can use single or double quotes around the text to create a string. But don’t forget to put the quotes totally. otherwise, it will give an error called reference error.
Single Quotes vs. Double Quotes vs. No Quotes
var myString1 = "Don't cheat!"; // works fine var myString2 = 'This book "Gitanjali" is amazing!'; // works fine var myString3 = "This book "Gitanjali" is amazing!"; // Syntax error var myString4 = Hello, PrograCoding; // Reference error
Don’t Mess Up
Don’t mess up with single or double quotes by using them together. It will give you syntax errors. You can also forget to put a quote at one side.
var a = "Hello, World!'; // syntax error var b = 'Hello, World!"; // syntax error var c = Hello, World"; // syntax error var d = "Hello, World; // syntax error var e = Hello, World!; // reference error
A single syntax error prevents to execute the source code. So be careful about the syntax error.
Using Strings in the Context
We can put a string directly into a statement called using in context. Let’s see an example:
document.getElementById("h1").InnerHTML = "Welcome!";
Notice that we have used strings directly without assigning it to a variable.
Connecting Strings Together
You can also use strings together by using much like arithmetical way. You can connect multiple strings using addition or plus sign. Let’s see an example:
var myText1 = "Hello, "; var myText2 = "PrograCoding!"; // connecting the two strings console.log( myText1 + myText2); // using context console.log( "Hello, " + "PrograCoding!");
What is Next?