Skip to content

JavaScript string variable | Basics

  • by

JavaScript string Variables in JavaScript are named containers that store a text value. For a variable to be a string type, the value assigned should be given in quotes.

A number within quotes will be considered only a string and not an integer.

var a = "Hello";
var b = "100";

JavaScript variable in a string

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>    
    var as = "This is 'a' 'String Test'";
    document.write(as);
  </script>  

</body>
</html>

Output:

JavaScript string variable

Special Characters: To use the special characters like tab, newline, backspace, double quotes, etc.. in string variables the following format should be used

CharacterCode to be used
Single Quote
Double Quote\”
Backslash\
Horizontal Tabt
New Linen
Back Spaceb
Carriage Returnr

Creating multiline strings in JavaScript

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, and variable interpolation among others, but most importantly for this question, they can be multiline.

Backticks delimit a template literal:

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

Javascript doesn’t have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"

JS variable inside a string

You can include a variable value inside a string using string interpolation or concatenation.

var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing

Comment if you have any doubts or suggestions on this Js variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading