JavaScript Syntax

JavaScript is a versatile programming language used primarily for web development. Its syntax, or the rules that dictate how the code should be written, is relatively easy to understand. Here, we'll break down the key components of JavaScript syntax with code examples.

Before we even start as you know if you want to learn Mathematics, Physics or Chemistry not only those almost all courses for you to find it easy you need to know and understand how the fomular was generated. So even programming languaged each of them has their way of creating variables, and now I will show you how the fomular and it will help you while trying to create any variable.

Here is the fomular:


variable-keyword  Identifier =  value;
            

The variable-keyword could be one of the three var, let or const it depend on what you want to store and we will explain each of then in the upcoming chapters. Then the Identifier could be anything you wish to call your data like: cat, book, dog or name of persons like: Muhammad. Then most use the symbol = it demostrating that you want to assign or store something to that variable which is the value.

Let's create one real-time example for better understanding. Check the below code.


var cat = "Samira";
            

Example

var cat = "Samira";
console.log(cat);
              

We have many type of data type let see how to create each one of them and store value of it.

Variables and Data Types

Variables are used to store data values. JavaScript has various data types, including strings, numbers, booleans, arrays, and objects.


var user = "Muhammad";
console.log(user);

var age = 30;
console.log(age);

var isStudent = true;
console.log(isStudent);

var fruits = ["apple","banana","orange"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

var person = {
  firstName:"Muhammad",
  lastName:"Ahmad"
};
console.log(person.firstName);
console.log(person.lastName);

            

Example


var user = "Muhammad";
console.log(user);

var age = 30;
console.log(age);

var isStudent = true;
console.log(isStudent);

var fruits = ["apple","banana","orange"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

var person = {
  firstName:"Muhammad",
  lastName:"Ahmad"
};
console.log(person.fileName);
console.log(person.lastName);
              

Conditional Statements

Conditional statements allow you to execute different code blocks based on certain conditions. Here is how to create it:

// If statement
if (age >= 18){ 
  console.log("You are an adult.");
}else {
  console.log("You are a minor.");
}

// Switch statement
var day = "Monday";
switch (day){ 
  case "Monday":
    console.log("It's Monday!");
    break;
  case "Tuesday":
    console.log("It's Tuesday!");
    break;
  default:
    console.log("It's some other day.");
}          
  

Example


// If statement
if (age >= 18){ 
  console.log("You are an adult.");
}else {
  console.log("You are a minor.");
}

// Switch statement
var day = "Monday";
switch (day){ 
  case "Monday":
    console.log("It's Monday!");
    break;
  case "Tuesday":
    console.log("It's Tuesday!");
    break;
  default:
    console.log("It's some other day.");
}
              

Loops

Loops are used to execute a block of code repeatedly. Here is how to create it:

// For loop
for(var i = 0; i < 5; i++){ 
  console.log(i);
}

// While loop
var count = 0;
while (count < 5){ 
    console.log(count);
    count++;
} 
            

Example


// For loop
for(var i = 0; i < 5; i++){ 
  console.log(i);
}

// While loop
var count = 0;
while (count < 5){ 
    console.log(count);
    count++;
}
              

Functions

Functions are blocks of reusable code that perform a specific task. Here is how to create it:

// Function declaration
function great(name){ 
  console.log("Hello " + name + "!");
}

// Function call
great("Muhammad");
            

Example


// Function declaration
function great(name){ 
  console.log("Hello " + name + "!");
}

// Function call
great("Muhammad");

Objects and Methods

Objects are collections of properties, and methods are functions associated with these objects. Here is how to create it:

// Object with method
var car = {
  brand:"Toyota",
  model:"Corolla",
  start:function(){ 
    console.log("Engine started.");
  }
};

// Method invocation
var myCar = car.start();
console.log(myCar);
            

Example

// Object with method
var car = {
  brand:"Toyota",
  model:"Corolla",
  start:function(){ 
    console.log("Engine started.");
  }
};

// Method invocation
var myCar = car.start();
console.log(myCar);

Arrays and Array Methods

Arrays are used to store multiple values in a single variable. Here is how to create it:

// Array methods
var numbers = [1,2,3,4,5];


// Adding elements
numbers.push(6);// [1, 2, 3, 4, 5, 6]

// Removing elements
numbers.pop();// [1, 2, 3, 4, 5]
            

Example

// Array methods
var numbers = [1,2,3,4,5];

// Adding elements
var myPush = numbers.push(6);
console.log(myPush);
console.log(numbers);// [1, 2, 3, 4, 5, 6]

// Removing elements
var myRemove = numbers.pop();
console.log(myRemove);
console.log(numbers);// [1, 2, 3, 4, 5]

Error Handling

JavaScript provides mechanisms for handling errors gracefully. Here is how to implement it:

// Try-catch block
try{ 
  // Code that might throw an error
  var result = 10/0;
  console.log(result);
}catch(error){
  console.log("An error occurred: "+ error.message);
}
            

Example

// Try-catch block
try{ 
  // Code that might throw an error
  var result = 10/0;
  console.log(result);
}catch(error){
  console.log("An error occurred: "+ error.message);
}

Understanding JavaScript syntax is essential for writing efficient and error-free code. With these fundamentals in mind, you can start building powerful web applications and interactive websites.

To understand JavaScript syntax well I need to tell you about this 5 concepts:

  • white space
  • case sensitivity
  • literals
  • identifiers
  • comments

White space

JavaScript does not consider white space meaningful. Spaces and line breaks can be added in any fashion you might like, even though this is in theory.

In practice, you will most likely keep a well-defined style and adhere to what people commonly use, and enforce this using a linter or a style tool such as Prettier.

For example, I like to always use 2 characters to indent.

Case sensitive

It should also be noted, before we begin, that Javascript is extremely case sensitive so if you're trying to code along with any examples make sure lowercase is lowercase and uppercase is uppercase. A variable named something is totally different from Somethingor SOMETHING.

For the most part Javascript is also a camel-cased language. That is, if you're trying to express more than one word you will eliminate the spaces, leave the first letter uncapitalized and capitalize the first letter of each word. Thus "get element by id"becomes "getElementByID".

The same goes for any identifier.

By contrast, HTML itself is NOT case sensitive.

Literals

We define as literal a value that is written in the source code, for example, a number, a string, a boolean or also more advanced constructs, like Object Literals or Array Literals:

              
30
"Test"
true;
["a","b","c"];
{color:"red", shape:"Rectangle"};
            

Identifiers

An identifier is a sequence of characters that can be used to identify a variable, a function, or an object. It can start with a letter, the dollar sign $or an underscore _and it can contain digits. Using Unicode, a letter can be any allowed char, for example, an emoji 😄 .

              
Test
test
myTest
_test
Test1
$test
            

The dollar sign is commonly used to reference DOM elements.

Some names are reserved for JavaScript internal use, and we can't use them as identifiers.

Comments

Comments are one of the most important parts of any program. In any programming language. They are important because they let us annotate the code and add important information that otherwise would not be available to other people (or ourselves) reading the code.

In JavaScript, we can write a comment on a single line using //. Everything after //is not considered as code by the JavaScript interpreter.

Like this:

              
// a comment
true //another comment
            

Another type of comment is a multi-line comment. It starts with /*and ends with */.

Everything in between is not considered as code:

              
/* another kind
of
comment

*/