Beginners Guide: Learning JavaScript syntax in 2022

Learning JavaScript syntax is the first step you must take in order to get started with JavaScript. In the following article, we will discuss JS syntax on scope, declaration, function, object, loops, operator, and comments. Writing JavaScript code will be a lot easier after you have understood syntax from the following topics.

1. Declaration Syntax in JS

The prerequisite for JavaScript declaration syntax is having knowledge of JS datatypes, get more information on datatypes from programiz.com/javascript/data-types

All the declarations in JS follow a similar syntax where datatype is followed by its user-defined name. For instance “var employee” code creates a declaration with the name “employee” with the variable datatype. Often a declaration is followed by its initialization for example, “var employee=”Employee name“; ” ie, variable declaration named “employee” is initialized with “Employee name” string.

// String declaration
var str = "String Value"

// Object declaration
var employee = {
  first-name: "John",
  last-name: "Doe"
}

// Number declaration
var num = 10

// Function variable declaration
var greet = (name)=>{
  return "Good Morning "+name;
}

2. Scope Syntax in JavaScript

The scope in JavaScript is enclosed within “{ }” ie, open and close curly braces, which is similar to Java syntax for scope. They enclose multiple lines of code generally in functions, class, object, etc. In addition, it is important to note JS scopes will impact the scopes during the run time of the code. Read more about JS scope from scotch.io/tutorials/understanding-scope-in-javascript.

Function and loop Scope: Scope syntax in function includes curly braces “{ }” to enclose the lines of code within the function or loop. The curly brace is opened at the end of function/loop declaration “{” and the curly brace is closed “}” at the end of the last line of code belonging to the function/loop.

Example of function scope syntax :

// Function that calculates perimeter and area of rectangle

function calculate (a,b){
 var perimeter = 2*(a+b);	   
 var area = a*b;
 console.log("The perimeter of rectange is ", perimeter);		
 console.log("The area of the rectange is ", area);	
}

Example of loop scope syntax :

// Function that number and its square from 0 to 9

for(var i=0;i<10;i++){
  let numSq = i*i;
  console.log("The value of loop variable: ",i);
  console.log("The squared value of loop variable: ",numSq);
}

Object Scope: Similar to function scope syntax, the list of all key-value pairs of properties and values is enclosed within “{ }” curly braces. It is important to note that the nested objects can be enclosed with multiple scopes.

// Object declaration with multiple key-value pairs.

let personObj = {
  Fname: "John",
  Lname: "Smith",
  age: 34 
}

3. Function Syntax

There are two types of functions in JavaScript, the first being independently declared directly within JS file, module, etc. Secondly declared function assigned to data type declaration such as “var”, “const”, etc.

The syntax for function declaration begins with the “function” keyword followed by the user-defined function name with arguments of the function enclosed in brackets, ie “function funcName (arg1,arg2,.. )”. The JS code of the function is enclosed in scope ie, “{}”. The last line of the function consists of a return statement for the function that will be returned on the function call which can be variable, string/number value, or also another function.
Syntax of function call includes function name with arguments of the function enclosed in brackets ie “funcName(arg1,arg2)”, using the function name alone will return the function itself.

// independent function declaration
function greet(name, age){
  return `Hello ${name}, your ${age} years old`
}

// function declaration with assignment
const greeting = function greet(name, age){
  return `Hello ${name}, your ${age} years old`
}

// function call
greet("John", 33); //"Hello John, your 33 years old"
greeting("John", 33); //"Hello John, your 33 years old"

Alternative syntax for the function is by declaring anonymous arrow function without any user-defined function name. Declaration of arrow function is similar normal function except “function func_name(arg1,arg2,..){ }” is replaced with “(arg1,arg2,..)=>{ }”. The arrow function has other differences in addition to the syntax which you can learn from video below or betterprogramming.pub

4. For and While loop Syntax

The loops in JavaScript are similar to other languages like java, python, etc which involve initialization, termination condition, and increment/decrement. The syntax of for loop begins with keyword “for(initialization;condition;increment/decrement){ //executable code }” and includes scopes to inclosed the code executed by the loop.

// for loop Syntax
for(initialization; condition; increment/decrement){
  //executable code 
}
// Items array with 3 string values 
var items = ["item1","item2","item3"]

// Iterate over all items array elements and log string 
for(var i=0; iThe item no ${i} value is ${items[i]}) }

In the case while loop “while(condition){ //executable code }”, unlike for loop initialization is prior and increment/decrement is done within the executable code.

// While loop syntax
while(condition){ 
  //executable code 
}
var items = ["item1","item2","item3"] 

// Prior initialization 
var i = 0; 

// Iterate over items array through while loop 
while(i < item.length){ 

  console.log(The item no ${i} value is ${items[i]}) 
  // Increment variable 
  i++; 
} 

5. JS Object Syntax

In JavaScript, any object initialized is an instance of the main “Object()” class. Even all data types such as string, number, etc are derived as child class from the “Object()” class. A JS object can be defined by creating a new instance of “Object()” class ie “new Object()” which returns an empty object. Once initialized, properties can be further attached to the empty object. Learn more from javascript.info/object.

// Declare empty object 
var employee = new Object(); 

// assign property values 
employee.name = "John"; 
employee.age = 33; 

console.log(employee); //{name: "John", age: 33}

However, an alternative method is through “{ }” scopes enclosing key-value pair. The object instance created can be assigned to a declaration like variable, constant, etc.

// object with "name" key and value "John", "age" key and value 33 
var employee = {name : "John", age : 33}; 

console.log(employee); //{name : "John", age : 33} 

6. JS Operators

To get the full potential of declarations it is essential to combine them with JS operators. Here is the list of all types of operators which you come across very often ( Read more from developer.mozilla.org/Expressions_and_Operators ):

  1. Assignment operators: type of operator used to assign a declaration with value through sign like “=”, “+=”, “-=”.
  2. Comparison operators: type of operator used to compare 2 declarations and return boolean value based on the comparison.
  3. Arithmetic operator: type of operator to perform an arithmetic operation between 2 declarations like addition, multiplication, subtraction, division, etc.
  4. String operators: type of operator used between 2 strings such as concatenation, addition, etc.
// assignment operators 
var num = 10; 
num += 2; 

// comparison operators 
console.log(num>10); //true 
console.log(num==12); //true 
console.log(num<=5); //false 

// arithmetic operator 
num++; 
num--; 

// string operators 
var greet="Hello "; 
console.log(greet+"there") //"Hello there" 
console.log(greet) //"Hello " 
console.log(greet+="there") //"Hello there" 
console.log(greet) //"Hello there" 

// Function that calculates perimeter and area of rectangle 
function calculate (a,b){ 
  var perimeter = 2(a+b); 
  var area = ab; 
  console.log("The perimeter of rectange is ", perimeter); 
  console.log("The area of the rectange is ", area); 
}

7. JS Comments

The aspect of code commenting is often ignored by beginners so it is important to understand that comments act as self-documentation, especially in large projects. Hence to become a JavaScript developer, you must regularly use comments for your reference and an external developer who is trying to understand the code. Read more from javatpoint.com/javascript-comment.

There are 2 types of comments in JavaScript that is a single line and multi-line comments. The single-line comment begins with “//” prefix and doesn’t extend to the next line. On contrary, multi-line comments begin with “/” prefix and end with “/” suffix which can extend for multiple lines.

//single line comment 
console.log("Demostrated single line comment") 

/*muti line comment */ 
console.log("Demostrated multi line comment") 

Conclusion

In this article, we covered JavaScript syntax for scopes, function, loop, operator, etc which shall allow you to understand most of the beginner-friendly JS code. However, it is important to note that writing more JS code is crucial for understanding most of the syntactical aspects of JavaScript.