JavaScript Syntax

Last updated on

JavaScript syntax is what you will use when writing and reading javascript code, it is the foundation of using this versatile programming language. It is the nom set of conventions and rules that tells you how to write your code so that the JavaScript engine can interpret it correctly.

From creating variables, functions, and loops to the way you write them, learning JavaScript syntax is important for writing efficient yet readable programs. In this section, we will go over some JavaScript and finish up with a few Definitions that I think are of good use.

Let’s get started with how JavaScript looks like when we use case-sensitive.

Understanding the Case Sensitivity in JavaScript

JavaScript is a case-sensitive language, which means it distinguishes between uppercase and lowercase. This applies everywhere throughout the language, like variable names or function names and even to identifiers. In other words, if in your code you’ve declared a Variable named myVariable, that is not the same as MyVariable or MYVARIABLE.

The case sensitivity is crucial to keep in mind when writing and debugging JavaScript code. A simple mix-up between lowercase and uppercase letters can lead to errors that might be challenging to track down. For example, if you reference myfunction() and not myFunction(), JavaScript will not recognize that as a function, and most probably this is going to raise an error.

Here is an example:

let myVariable = "Case sensitive";
let MyVariable = "Not the same as myVariable";

console.log(myVariable); // Outputs: Case sensitive
console.log(MyVariable); // Outputs: Not the same as myVariable

In such situations following uniform naming conventions is a good practice to avoid case-sensitivity-related problems. When you have consistencies in the way a particular feature or variable is spelled, like how most devs write camelCase (myVariableName) it makes for easier reading and fewer things to mentally slip on when writing out your code. This makes our code cleaner, and more reliable and we will have fewer errors in development when respecting that JavaScript is case-sensitive.

So, let’s move on to the following section to understand how to write JavaScript with camelCase.

Using CamelCase in JavaScript

CamelCase is used more often in a naming convention where the first word we write down is lowercase, and every other word starts with an upper-case letter like thIsLibrary. JavaScript supports this convention for defining variables, functions, or object properties which helps you in keeping your code clean and readable.

Moreover, we can use the CamelCase in the naming of JavaScript variables and functions. So for example instead of naming the variable like this my_variable_name, you can name it like this myVariableName.

You also can do similar in the function names, here is an example:

let myFavoriteColor = "Blue";
function calculateTotalAmount() {
    // Function logic here
}

Whitespace and Line Breaks in JavaScript

whitespace and line breaks in JavaScript are all those spaces you leave around your code to make it look nice. Yes, the computer does not need extra spaces or line breaks to run your code but it helps you and others understand what is coded.

For example, spaces around operators like + and = make the code clearer:

let x = 10;
let y = 20;
let sum = x + y;

One of the more important aspects of JavaScript is variables and data types. Let’s move on to the following section to gain an overview.

One more thing else Semicolons can be used but are optional. So you can put it at the end of the code line or don’t use it.

Here is an example:

let x = 10
let y = 20
let z = x + y; // Semicolons can be used but are optional

Anyway, let’s take a look at some of the basic syntax elements of the JavaScript language, such as variables, data types, operations, expressions, and more.

Variables and Data Types

Like any other language, JavaScript has variables that are used to store values. The way of declaring a variable is to call var, let, or const for the respective scope and behavior.

Here is a quick example of variables in JavaScript.

// Example of variable declaration using 'var'
var message = "Hello, JavaScript!";

// Example using 'let'
let count = 10;

// Example using 'const'
const pi = 3.14;

Moreover, JavaScript supports various data types such as strings, numbers, booleans, arrays, and objects. You just need to take a look at all of them to consider the rules of JavaScript syntax when you write code.

So, let’s take a look at how to write comments in JavaScript code.

Comments in JavaScript

Before we go any further, I should be clear that comments in your code are invaluable. Comments are like margin notes, they make code more readable and help you remember what you were thinking at that exact moment.

In JavaScript, single-line comments begin with //, while multi-line comments are enclosed between /* and */.

// This is a single-line comment

/*
   This is a
   multi-line comment
*/

No programming language works without operators and expressions! JavaScript has its considerations also for that when you write its syntax. In the following section, you will take just an overview of that. let’s move on.

Operators and Expressions

JavaScript syntax has a lot of operators that act on variables and values. What are these operators? These include arithmetic, assignment, comparison, logical, and bitwise operations. Good knowledge of operators and their ways is key to writing the most effective code.

Here is an example.

// Arithmetic operators
let sum = 5 + 3; // Addition
let difference = 10 - 4; // Subtraction
let product = 6 * 2; // Multiplication
let quotient = 8 / 2; // Division

// Comparison operators
let isEqual = (5 === "5"); // Strict equality

// Logical operators
let andResult = (true && false); // Logical AND
let orResult = (true || false); // Logical OR

So, once you understand the basics, next is understanding control flow structures. These structures are what ensure which command get executed first so that applications can be created to interact with them dynamically and more effectively. Let’s move on.

JavaScript Syntax for Conditional Statements

JavaScript provides conditional statements like ifelse if, and else for executing different blocks of code based on specified conditions. It is very important because you may need to change from one of these statements to another so that you can implement decision-making logic in your programs.

let grade = 85;

if (grade >= 90) {
    console.log("A");
} else if (grade >= 80) {
    console.log("B");
} else {
    console.log("C");
}

Furthermore, the ternary operator (? :) provides a shorthand for writing conditional expressions, helping to keep the code short and readable.

Anyway, let’s move into the section below to understand why loops are in the JavaScript language syntax.

JavaScript Syntax for Loops

Loops are essential for iterating over arrays, and objects, or executing a block of code multiple times. JavaScript supports forwhile, and do-while loops, each with its distinct use cases.

Here is an example.

// Example of a 'for' loop
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// Example of a 'while' loop
let count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

// Example of a 'do-while' loop
let x = 0;
do {
    console.log(x);
    x++;
} while (x < 2);

Let’s take an overview of functions with expressions.

JavaScript Syntax for Function Declarations vs. Expressions

Both include function declarations and function expressions. This will grant you the flexibility in your coding approach to switch smoothly between these forms.

// Function declaration
function greet(name) {
    return "Hello, " + name + "!";
}

// Function expression
const greetExpression = function(name) {
    return "Hello, " + name + "!";
};

Moreover, the arrow function syntax was introduced in ECMAScript 6 and enables you to write shorter functions with less verbosity, at least for one-liner functions.

Anyway, let’s move into the scope and closures in the following part.

JavaScript Syntax for Scope and Closures

The scope refers to where in your code you can access variables and functions. Scope is of two types in JavaScript; Global scope and local Scope.The closure occurs when a function retains access to its lexical scope, even after the function that created it has finished executing.

Here is an example.

// Function scope example
function exampleFunction() {
    if (true) {
        var localVar = "I am local!";
    }
    console.log(localVar); // Outputs: I am local!
}

// Block scope example (using 'let' or 'const')
function blockScopeExample() {
    if (true) {
        let blockVar = "I am local!";
    }
    console.log(blockVar); // Error: blockVar is not defined
}

Objects and properties are significant aspects of JavaScript. Let’s take a brief look at them.

JavaScript Syntax for Objects and Properties

You can look at objects in JavaScript as key-value pair containers, to represent real-world things. Switching from an object literal notation to constructor functions is one of the main keys in how objects can be used and manipulated.

// Object literal notation
let person = {
    name: "John",
    age: 30,
    isStudent: false
};

// Constructor function
function Person(name, age, isStudent) {
    this.name = name;
    this.age = age;
    this.isStudent = isStudent;
}

let newPerson = new Person("Jane", 25, true);

Let’s take a brief look at prototypes and inheritance in JavaScript.

JavaScript Syntax for Prototypes and Inheritance

The typical way in how JavaScript implements object orientation is through Prototypes and Inheritance. Easily move from object prototypes to constructor functions and then on to the class syntax introduced in ES6.

// Prototypal inheritance
function Animal(name) {
    this.name = name;
}

Animal.prototype.sound = function() {
    console.log("Some generic sound");
};

function Dog(name, breed) {
    Animal.call(this, name);
    this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.sound = function() {
    console.log("Woof!");
};

In the next section, you will gain an overview of callbacks in JavaScript.

Callback Functions

One of the traditional ways JavaScript deals with asynchronous operations is by using callback functions. Here is where the callback pattern becomes extremely important as we move from simple callbacks into more complex scenarios.

Here is an example.

function fetchData(callback) {
    // Simulating asynchronous data fetching
    setTimeout(function() {
        let data = "Fetched data";
        callback(data);
    }, 1000);
}

fetchData(function(result) {
    console.log(result);
});

Let’s delve into promises and async/await.

Promises and Async/Await

Promises provide a more structured and orderly way to work with asynchronous operations. By moving from callbacks to promises and using the new async/await syntax we have dramatically improved both code readability and maintainability.

function fetchData() {
    return new Promise((resolve, reject) => {
        // Simulating asynchronous data fetching
        setTimeout(() => {
            let success = true;
            if (success) {
                resolve("Fetched data");
            } else {
                reject("Error fetching data");
            }
        }, 1000);
    });
}

async function fetchDataAsync() {
    try {
        let result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

fetchDataAsync();

Let's summarize it.

Wrapping Up

Learning JavaScript syntax includes simple concepts like its primitive elements and control flow structures to the more advanced features related to functions, object-oriented ideas as well how to deal with asynchronous programming. You’ll need to understand how and when to switch between those concepts to write code efficiently, read it clearly, and not shoot your foot.

Thank you for reading. Happy coding!

Frequently Asked Questions (FAQs)

  • What does it mean when we say that JavaScript is a case-sensitive language?

    This means in JavaScript, whatever you do is case-sensitive — telling between uppercase letters and lowercase letters. Identifiers for example: myVar and myvar are different counters.
  • How does case sensitivity affect variable and function names in JavaScript?

    Variable/function names are case-sensitive (myVar and myvar are two different variables/functions) in JavaScript. It is all very well but one thing that you must always watch out for is to keep from making errors.
  • Why is it important to remember JavaScript’s case sensitivity when debugging code?

    When debugging errors, case sensitivity in JavaScript is crucial because, for methods/functions, etc., the first letter must be capitalized, and if it needs to remain lowercase, all should start with a small letter.
  • What happens if you mistakenly reference myfunction() instead of myFunction() in JavaScript?

    In Javascript, this would throw an error as JavaScript is case-sensitive and it considers myfunction() is a different function from myFunction().
  • What is camelCase, and how is it used in JavaScript?

    Camel Case — It is a naming style in Javascript where the first word starts with a lowercase letter and every other subsequent should be capitalized e.g myVariableName.
  • Why is camelCase preferred in naming variables and functions in JavaScript?

    Camel case improves the readability because words can be separated but no white spaces or underscores as well in variable and function names which is convenient for JavaScript.
  • What role do whitespace and line breaks play in JavaScript code?

    In JavaScript, white space and line breaks are there for code readability which does not affect the execution of your code. And in most other places, JavaScript will ignore them.
  • Are semicolons mandatory at the end of a line of code in JavaScript?

    JavaScript has semicolons, which are not required because of automatic; insertion (ASI), but it is recommended to use them as a basic rule to avoid potential errors and code explanations.
Share on: