var str = new String("I learn JavaScript");
alert( str ); // Show content of your string variable
// Double quotes:
var str1 = "I learn JavaScript";
// Exact same string, but declared with single quotes:
var str2 = 'I learn JavaScript';
Tip: to use double-quotes or single quotes in a string, escape these characters. You can use single quotes inside double-quoted strings, and double quotes inside single-quoted strings: when you need the same quote as the surrounding ones, escape it with a backslash (\) in front of it: var str1 = "Let's include \"this\" in the middle"; // Single quote is ok
var str2 = 'Let\'s include "this" in the middle'; // Double quotes are ok
var jsIsCool = true;
var str = jsIsCool.toString(); // Same as declaring: var str = "true";
Note: JavaScript will often perform an automatic type conversion for you. The alert() method automatically converts its arguments to string - no work on your part: var num = 3.14;
When using the concatenation operator (plus sign) between strings and other data types, everything will be converted to a string - let's do it and check if the result is a string, using the typeof operator:
alert( num ); // num still a number, but its value was auto-convertedvar str = "The value of pi is " + 3.14 + " (approximately)";
alert( typeof str +"\n---\n"+ str ); // check data type + show value
// array of strings and a number (cups of veggies you need daily :)
var veggies = ["potatoes", "beans", "peas", "spinach", 3];
var str = veggies.join("\n"); // each element on its own line
alert( typeof str +"\n---\n"+ str ); // check data type + show value
// Count digits in a number: no string variable ever declared!
alert( "There are " + "12345".length + " digits in this number" );
// Single quotes - PHP interpreter will not parse:
$str1 = 'I learn PHP';
echo $str1; // prints exact text
// Double-quotes: interpreter will look for PHP code
$year = date('Y');
$str2 = "The current year is $year"; // variable inside double-quotes
echo $str2; // prints "The current year is 2024"
$str3 = 'The current year is $year'; // variable inside single-quotes
echo $str3; // prints "The current year is $year"