JavaScript Syntax


JavaScript Syntax

JavaScript syntax is the set of rules that define a correctly structured JavaScript program. JavaScript is made up of JavaScript statements that are inserted within HTML elements on a web page or in an external JavaScript file with the .js extension.

The following example shows how JavaScript statements look like:

Example

var x = 7; 
var y = 12;
var sum = x + y;
document.write(sum); // Show variable value

Semicolon

JavaScript statements are separated by a semicolon. However, it is not mandatory to end a statement with a semicolon, but it is recommended.

<script>
var one = 1; two = 2; three = 3; //three different statements var four = 4; //single statement
var five = "Five" //single statement without ;
</script>

Case Sensitivity in JavaScript

JavaScript is a case-sensitive scripting language. So, name of functions, variables and keywords are case sensitive.

For example,  The variable myVar must be typed myVar not MyVar or myvar, Name is not equal to name etc.

Example

var myVar = "Tutorials 
Trend!";

console.log(myVar);
console.log(MyVar);
console.log(myvar);

If you look at the browser console by clicking the F12 key on your keyboard, you'll notice something like "Uncaught ReferenceError: MyVar is not defined."

JavaScript Syntax

JavaScript Comments

A comment is a single or multiple-line statement that provides information about the current program. A comment is simply a line of text that is completely ignored by the JavaScript interpreter. Comments are not for execution.

JavaScript support single-line as well as multi-line comments.

  1. Single-line comments begin with a double forward slash (//), followed by the comment text.
  2. To write multiple lines of comments between /* and */

Here's an example:

Example

// This is for single line comment in JavaScript program

document.write("Tutorials Trend!");

Whereas, a multi-line comment begins with a slash and an asterisk (/*) and ends with an asterisk and slash (*/). Here's an example of a multi-line comment.

Multiline Example

/* This is for multi line comment in JavaScript program  */

document.write("Tutorials Trend!");

Keywords

Keywords are reserved words in JavaScript, that cannot be used as variable names or function names. The following table lists some of the keywords used in JavaScript.

JavaScript Reserved Keywords

var function if
else do while
for switch break
continue return try
catch finally debugger
case class this
default false true
in instanceOf typeOf
new null throw
void width delete

Prev Next