Web Development

JavaScript Syntax

JavaScript Syntax is section 2 of Beginner’s Guide to JavaScript.

As we said in our introduction article JavaScript is a client side scripting language. Scripting languages are lightweight programming languages. That’s why it is totally different from Oracle’s Java language (Previously known as Sun’s) even it has the name ‘Java’. But if you are good at Java language, you’ll find similarities in JavaScript syntax.

Sentences of a programming language is called statements. So how this sentences can be constructed is defined by the language syntax, the thing that we’re going to discuss in here. Most important thing to remember is JS is case sensitive. For example variables mark is not the same variable named Mark. Function myFunc() is not same as MyFunc(). When you define a variable you should use it as var, not as Var.

JavaScript Literals

Literal is a constant value. There are several types of literals in the JavaScript Language. Most of the times you’ll see this as data types.

Number Literals

Written with or without decimals, and with or without scientific notations.

var a = 3.14;

var a = 1001;

var a = 123e5;

var a = 12300000;

String Literals

Written with double or single quotes.

var a = ‘dog’;

var a = “dog”;

Expression literals

Written to compute values.

var a = 2 * 10;

var a = 2+ 10;

Array literals

Written to define an array. With square brackets and separated by commas. Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

var a = [88, 5, 166, 465336, 22, 15550];

Object literals

Written to define an object with curly braces. Object properties are written as name:value pairs, separated by commas.

var a = {type:“Dog”, name:“Timmy”, age:2, color:“brown”}

Function literals

Written to define a function.

var a = function myFunc(a, b) { return a / b;};

JavaScript Variables

Variables are used to define a location of the memory where the data values are stored. Also we can say it is a “containers” for storing data values. We give a unique name to that for human readability which are called identifiers. JavaScript uses the var keyword to define variables. An equal sign is used to assign values to variables.

[code language=”js”] var length; //Variable declared without a value will have the value undefined.
length = 6;

In this example length variable stores the value 6. In the browser you’ll see the output 6.

The value of a variable with no value is undefined. Variables can be emptied by setting the value to null.

You can declare many variables in one statement. Start the statement with var and separate the variables by comma.

var name= “Timmy”, age = 2, type= “Dog”;

If you re-declare a JavaScript variable, it will not lose its value.

var name= “Timmy”;

var name;

In the above example still the name got “Timmy” value assigned to it.

JavaScript Operators

You can use the following operators in JS.

Arithmetic Operators 

  • Add +
  • Subtract –
  • Multiply *
  • Division /

JavaScript uses arithmetic operators to compute values.

[code language=”js”] document.write(4+2+6);

You’ll see the output as 12 in the browser.

Assignment Operator =

This is not an “equal to” operator.

[code language=”js”] var a = 3;
var b = 7;
var c = 5;
var ans = a+b+c;

You’ll see the output as 15 in the browser.

Bitwise Operators

  • Bitwise AND &
  • Bitwise OR |
  • Bitwise XOR ^
  • Bitwise NOT ~
  • Left shift <<
  • Sign propagating Right Shift  >>
  • Zero fill right shift >>>

Logical Operators

They are used to determine the logic between variables or values.

  • Logical AND &&
  • Logical OR ||
  • Logical NOT !
[code languague=”js”] var x=3;
var y=8;

document.write(x < 10 &amp;amp;&amp;amp; y > 5); // Output true
document.write(x == 5 || y == 5); // Output false
document.write(!(x == y)); // Output true

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

  • Equal to ==
  • Equal value and equal type ===
  • Not equal !=
  • Not equal value or not equal type !==
  • Greater than >
  • Less than <
  • Greater than or equal to >=
  • Less than or equal to <=
[code languague=”js”] var x=3;

document.write(x < 10); // Output true document.write(x == 5); // Output false document.write(x != 6); // Output true document.write(x === 3); // Output true document.write(x === '3'); // Output false document.write(x !== '3'); // Output true document.write(x > 6); // Output false
document.write(x >= 3); // Output true
document.write(x <= 7); // Output true [/code] Conditional Operator

Conditional operator assigns a value to a variable based on some condition. Syntax is goes like follows.

variablename = (condition) ? value1:value2

Most notable usage of this operator is shown below.

[code language=”js”] var comment = (mark > 50) ? “Good”:”Bad”;

If the variable mark is a value above 50, the value of the variable comment will be “Good”, otherwise the value of comment will be “Bad”.

JavaScript Statements

A computer program is a sequences of “executable commands” called statements and they are separated by using a semicolon. The purpose, of the statement is to tell the browser what to do. Following is a example of a statements and see how it ends with semicolons. But note down that it is really not necessary to type semicolon at the end of the line because JS can input it by itself when the compilation goes on. So semicolon is optional. But if you write more statements in a one line, then the semicolon is required except for the last one.

[code language=”js”] //in different lines
document.getElementById(“demo”).innerHTML = “My First JavaScript Statement”;
x = 7 + 3;
y = x * 2;

//in same line
x = 7 + 3;y = x * 2;

In your JS code what you are doing is writing sequence of statements. Commanding browser what to do. Each statement is executed by the browser in the sequence they are written.

Most important thing is JavaScript ignores extra spaces. You can add white spaces to your script to make it more readable. That’s why indentation is recommended when writing a JS code.

JavaScript Keywords

A JavaScript statement often starts with a keyword. The var keyword tells the browser to create a new variable like as we mentioned before.

JavaScript Identifiers

All programming languages must identify all variables with unique names. These unique names are called identifiers like as we mentioned before. Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Reserved words (like JavaScript keywords) cannot be used as identifiers. Most of the time identifies are written with camel-case. It can have short names (like x and y) or more descriptive names (age, mark, totalMarks)

JavaScript statements often start with a statement identifier to identify the JavaScript action to be performed. Statement identifiers are reserved words and cannot be used as variable names.

statement identifier Description
break Terminates a switch or a loop
catch Marks the block of statements to be executed when an error occurs in a try
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging
do … while Executes a block of statements, and repeats the block, while a condition is
for Marks a block of statements to be executed, as long as a condition is true
for … in Marks a block of statements to be executed, for each element of an object
(or array)
function Declares a function
if … else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
throw Throws (generates) an error
try Implements error handling to a block of statements
var Declares a variable
while Marks a block of statements to be executed, while a condition is true

JavaScript Comments

Anything after double slashes // is treated as a comment, ignored, and not executed. It is called single line comment.  When we use /* on  something at a start and  */  on something at the end this is called multi-line comments or block comments. The text inside those two symbols are ignored and not executed. Comments in JS are used for the same purposes as we mentioned in our HTML and CSS tutorials.

JavaScript Data Types

JavaScript variables can hold many data types: String, Number, Boolean, Array, Object, Null, Undefined.. We do not specifically define the data type of a variable because JS automatically identify what datatype is it. So we called it JavaScript has dynamic types. This means that the same variable can be used as different types.

var y;               // Now x is undefined
var y = 2;           // Now x is a Number
var y = “Dog”;      // Now x is a String

In JavaScript texts are called strings or text strings. When you assign a string value to a variable, you put double or single quotes around the value.

varname = “Timmy”;   // Using double quotes
varname = ‘Timmy’;   // Using single quotes

But remember starting and ending code should be identical. And you cannot use the same type of double quotes inside of it if escape characters were not used, but you can use other type of double quotes.

var answer = “It’s alright”;             // It’s alright
var answer = “He is called ‘Johnny'”;    // He is called ‘Johnny’
var answer = ‘He is called “Johnny”‘;    // He is called “Johnny”

When you assign a numeric value to a variable, you do not put quotes around the value. If you put quotes around a numeric value, it will be treated as a text string.

Booleans can only have two values: true or false and are often used in conditional testing.

You can use the JavaScript typeof option to find the type of a JavaScript variable.

typeof “Dog”                 // Returns string
typeof34// Returns number
typeoftrue// Returns boolean
typeof [1,2,3,4]           // Returns object. In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object.
typeof {name:‘Timmy’, age:3}  // Returns object

Most important thing to remember is do not declare String, Number, and Boolean as Objects even you can do that. Because they’ll complicate your code and slow down execution speed.

var x = new String();          // Declares x as a String object
var y = new Number();          // Declares y as a Number object
var z = new Boolean();         // Declares z as a Boolean object

JavaScript Functions

JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket, and end with a right curly bracket. {   } The purpose of a block is to make the sequence of statements execute together. We called it a function. JavaScript statements written inside a function can be invoked and reused many times.

JavaScript Character Set

JavaScript uses the Unicode character set. Unicode covers (almost) all the characters, punctuations, and symbols in the world.


In the next few sections we are going to coverup most of the above mentioned topics.

What’s Next?

Learn what is JavaScript Scope

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.

About the author

Sandeep Likhar

Sandeep Likhar from Indore India, Blogger, eBook Designer and Founder of LetsDnD. Having five years of experience in industry as a Digital Publishing Expert and eBook Converter providing services to Authors, Publishers and distributors worldwide. Proficient in converting books into various formats HTML, epub, mobi, word, PDF including all major online platforms iTunes, Kobo, Kindle, Createspace, B&N, Smashwords and more.

Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.