In this article let us look at Syntax and Basic Rules, which we need to follow while writing JavaScript code. You can refer to the tutorial Hello World example using JavaScript to learn how to create and run a Javascript Program.
JavaScript is case-sensitive. This means that foo is not the same as Foo. Test is not same as test.
The JavaScript has two syntactic distinctions. one is statement & the other one is expression.
A JavaScript statement performs some action but does not produce any value. Optionally they end with a semicolon.
A Typical Javascript program consists of several such sequences of statements and they control the flow of the program. The JavaScript interpreter executes these statements one by one in the order they are specified in the Program.
For Loops and if statements are examples of statements.
//statement that create a variable
var message;
//statement that assigns “Hello World” to message variable
message=”hello world”;
//statmenent that prints out console log
console.log(message);
//
; the semicolon is used to indicate the end of a statement.
For Example
var message;
message=”hello world”;
console.log(message);
But, they are optional if you use a single line for each statement
For Example, this is also valid
var message
message=”hello world”
console.log(message)
But, they are required if you have multiple statements in a line
For Example
var message ; message=”hello world” ; console.log(message) ;
They are also required in some cases where interpreter fails to correctly identify the end of statement.
For Example
var c = 1 + 2
(1 + 2).toString()
An expression is any valid unit of code that resolves to a value. They can appear anywhere in the code. They can be part of the function arguments or right side of an assignment, etc. The Expressions are often part of a statement.
When interpreter sees an expression it retrieves its value and replaces expression with new value. The following codes are examples of the expressions
//Simple Expression that produces numeric value 5
5;
// Airthmetic Expression that produces numeric value 15
5+15;
//String expression that evaluates to 'hello world' string
'hello' + 'world'; //
//Argument in a function call are expressions
addNum(5,15)
You can use spaces, tabs, and newlines anywhere in the Javascript Program. The Javascript interpreter ignores them. Use tabs & spaces to neatly format or indent your code. It makes the code easy to read & understand.
Comments
The JavaScript allows us to add single line comments or Multi line comments
Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment.
//this is a single-line commentNested comments are not supported
/* /*This Comments not allowed*/ */