Skip to main content

Command Palette

Search for a command to run...

JavaScript Basics: A Beginner's Guide to Syntax, Variables, Operators, Control Flow, and Loops

Updated
•11 min read
JavaScript Basics: A Beginner's Guide to Syntax, Variables, Operators, Control Flow, and Loops
C

I am a Software Developer who is so passionate about teaching and writing.

Introduction

JavaScript is a popular programming language that powers the interactive elements you see on websites and web applications. Whether it's a dynamic button, a form validation, or a captivating slideshow, JavaScript brings websites to life.

If you're an aspiring programmer or someone new to coding, you're in the right place. In this beginner's guide, we'll provide clear explanations and concise code examples to help you grasp the core concepts of JavaScript. By the end, you'll have a solid foundation in JavaScript basics, empowering you to take on more complex programming challenges.

So, let's get started on this exciting journey and unlock the potential of JavaScript programming. Get ready to explore the syntax, variables, operators, control flow, and loops. These are the fundamental elements that will pave the way to your programming success.

Let's dive in!

Table of Contents

  1. Introduction to JavaScript Syntax

  2. Working with Variables

  3. Understanding Operators

  4. Control Flow: Conditional Statements

  5. Looping with JavaScript

  6. Conclusion

Introduction to JavaScript Syntax

Syntax refers to the rules and structure of a programming language. Understanding JavaScript syntax is essential for writing code correctly. Let's explore the basic elements of JavaScript syntax:

Statements

JavaScript programs are made up of statements. Each statement performs a specific action and ends with a semicolon (;).

Code Example:

var message = "Hello, World"; //This is a statement

Comments

Comments are notes that you can add to your code to explain what it does. They are ignored by the computer and help understand your code later on. You can add single-line comments (//) or multi-line comments (/* ... */).

Code Example:

// This is a single-line comment  
/* This is a multi-line comment,  
it extends to two or more lines */

Whitespace

Spaces, tabs, and line breaks are examples of whitespace. JavaScript ignores most whitespace, except when it is necessary to separate code elements.

Merging the above three, let's look at this code snippet:

// JavaScript Syntax Example
var message = "Hello, World!";
console.log(message);

In the above example, you can see the single-line comment, then we create a variable named message and assign it the value Hello, World!. The console.log() function is used to display the value of the message variable in the browser console.

Working with Variables

Variables are like containers that store information. They allow you to store and manipulate data in our programs. Here's how you work with variables in JavaScript:

Variable Declaration

To create a variable, you use the var, let, or const keyword followed by the variable name.

Variable Assignment

You can assign a value to a variable using the assignment operator which is represented by equals sign(=).

Data Types

Variables can hold different types of data, including strings, numbers, booleans, arrays, and objects. You can read the Data Structures tutorial to grab more knowledge on data types.

Here is a code example for the above explanation:

// Variables Example
var name = "John";
var age = 25;
var isStudent = true;

console.log(name, age, isStudent);

In the above example, variable names(name, age, isStudent) are declared with the var keyword. Then, the assignment operator(=) is used to assign values: string("John"), number(25), and boolean(true) to the variables.

Understanding Operators

Operators will allow you to perform actions on variables and values. They help you manipulate and compare data.

Here are some commonly used operators:

Assignment Operators

It's used to assign values to variables.

Here is a code example using the assignment operator (=):

let x = 5;
let y = 2;

x += y;  // the same as x = x + y
console.log(x); // output: 7

y -= 1;  // the same as y = y - 1
console.log(y); // output: 1

Arithmetic Operators

They perform basic mathematical operations, such as addition (+), subtraction (-), multiplication (*), and division (/).

Code example:

let x = 5;
let y = 2;

let addition = x + y;
console.log(addition); // output: 7

let subtraction = x - y;
console.log(subtraction); // output: 3

let multiplication = x * y;
console.log(multiplication); // output: 10

let division = x / y;
console.log(division); // output: 2.5

Comparison Operators

These compare values and return true or false, such as greater than (>), less than (<), equal to (==), strictly equal to (===), and not equal to (!=).

Code example:

let x = 5;
let y = 2;

console.log(x > y); // output: true
console.log(x < y); // output: false
console.log(x == y); // output: false
console.log(x != y); // output: true  
console.log(x === y); // output: false

Logical Operators

These help us combine conditions and make decisions using logical AND (&&) and logical OR (||).

Code example:

let x = 5;
let y = 2;

console.log(x > 3 && y < 5); // output: true
console.log(x > 3 || y > 5); // output: true

Control Flow: Conditional Statements

Control flow in JavaScript allows you to dictate the order in which instructions are executed.

Conditional statements are a fundamental aspect of control flow, as they enable you to make decisions in your code based on certain conditions.

You can use conditional statements to execute different blocks of code depending on whether a specified condition evaluates to true or false.

Here are the types of conditional statements: the if statement, the else if statement, and the switch statement.

The if statement

The if statement is used to execute a block of code if a given condition evaluates to true. If the condition is false, the code block is simply skipped.

The basic syntax of the if statement is as follows:

if (condition) {
  // Code to be executed if the condition is true
}

Let's say we want to check if a given number is positive or not:

Code example:

let num = 5;

if (num > 0) {
  console.log(The number is positive.);
}

In the example above, the condition num > 0 is true because the value of num is 5. As a result, the message The number is positive. will be printed on the console.

The else if statement

The else if statement allows you to test multiple conditions and execute different code blocks based on which condition is true.

It is used after the if statement and before the optional else statement.

Here is the basic syntax of else if statement:

if (condition1) {
  // Code to be executed if condition1 is true
} else if (condition2) {
  // Code to be executed if condition2 is true
} else {
  // Code to be executed if all conditions are false
}

Using the previous example, add a check for zero and negative numbers.

Code example:

let num = 5;

if (num > 0) {
  console.log(The number is positive.);
} else if (num === 0) {
  console.log(The number is zero.);
} else {
  console.log(The number is negative.);
}

In this case, the condition num > 0 is true, so the first code block is executed, and you get the output The number is positive.

It's essential to use proper indentation to make your code more readable, especially when dealing with nested conditional statements.

The switch statement

The switch statement is a control flow statement that allows you to execute different code blocks based on different conditions.

It's useful when you have multiple possible conditions to evaluate, and it provides a more concise and readable alternative to using multiple if-else statements.

Here is the basic syntax of the switch statement:

switch (expression) {
  case value1:
    // code to be executed when expression matches value1
    break;
  case value2:
    // code to be executed when expression matches value2
    break;
  case value3:
    // code to be executed when expression matches value3
    break;
  // more cases...
  default:
    // code to be executed when none of the cases match expression
    break;
}

How does the switch statement work?

  • The expression is evaluated once and compared with the values in the cases. If the expression matches a case value, the code block associated with that case is executed.

  • The break statement is used to exit the switch statement and prevent the execution of subsequent cases.

  • If none of the cases match the expression, the code block associated with the default case is executed (if present). The default case is optional and acts as a fallback when none of the cases match the expression.

Here's a code example of the switch statement:

let day = 'Monday';

switch (day) {
  case 'Monday':
    console.log(It's the start of the week.);
    break;
  case 'Tuesday':
    console.log(Another day of work.);
    break;
  case 'Wednesday':
    console.log(Halfway through the week.);
    break;
  case 'Thursday':
    console.log(Almost there, just one more day.);
    break;
  case 'Friday':
    console.log(TGIF! Weekend is near.);
    break;
  default:
    console.log(Enjoy your weekend!);
    break;
}

In the example above, the code checks the value of the day variable and executes the corresponding code block based on the matching case. If the value of day is Monday, it will print It's the start of the week. to the console.

Looping with JavaScript

Looping refers to the process of executing a block of code repeatedly until a certain condition is met. It allows you to automate repetitive tasks and perform operations on a set of data.

There are several types of loops in JavaScript:

for loop

The for loop is commonly used when you know the number of iterations in advance. It consists of an initialization, a condition, an increment or decrement statement, and the code block to be executed.

Here is the basic syntax of a for loop:

for (initialization; condition; increment/decrement) {
  // code to be executed
}

Code example of a for loop that prints numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log(i); // prints 1, 2, 3, 4, 5
}

In the above example, the for loop initializes a variable i to 1, checks if i is less than or equal to 5, executes the code block console.log(i), and increments i by 1 in each iteration. The loop continues until i is no longer less than or equal to 5.

while loop

The while loop is used when the number of iterations is not known beforehand. It repeatedly executes the code block as long as the specified condition is true.

Here is the basic syntax of while loop:

while (condition) {
  // code to be executed
}

Code example of a while loop that print numbers from 1 to 5:

let count = 1;

while (count <= 5) {
  console.log("Count: " + count);
  count++;
}

In the above example, while loop prints the value of count from 1 to 5, continuing as long as count is less than or equal to 5. It logs each value using console.log and increments count by 1 after each iteration. The loop terminates when count reaches 6.

do-while loop

The do-while loop is similar to the while loop, but the condition is evaluated after the code block is executed. This guarantees that the code block is executed at least once.

Here is the basic syntax of do-while loop:

do {
  // code to be executed
} while (condition);

Code example of do...while loop:

let i = 1;

do {
  console.log(i);
  i++;
} while (i <= 5);

In the above example, the do-while loop will execute the code block at least once, regardless of the condition. The loop will continue executing as long as i is less than 5. In each iteration, the value of i is logged to the console using console.log(i), and then i is incremented by 1 using the i++ statement. The loop terminates when i becomes greater than 5.

for...in loop

The for...in loop is used to iterate over the properties of an object. It allows you to loop through the keys or property names of an object.

Here is the basic syntax of for..in loop:

for (let key in object) {
  // code to be executed
}

Code example of using a for...in loop to iterate over the properties of an object:

const person = {
  name: 'John',
  age: 30,
  occupation: 'Developer'
};

for (let key in person) {
  console.log(key + ': ' + person[key]);
}

In the above example, the for...in loop iterates over each property in the person object. On each iteration, the key variable represents the current property name. We can access the corresponding value using person[key]. In the loop's code block, the property name and its value are logged to the console.

for...of loop

The for...of loop is introduced in ES6 and is used to iterate over iterable objects such as arrays, strings, maps, sets, etc. It allows you to loop through the values of the iterable.

Here is the basic syntax of a for...of loop:

for (let element of iterable) {
  // code to be executed
}

Code example of a for...of loop:

const fruits = ['apple', 'banana', 'orange'];

for (let fruit of fruits) {
  console.log(fruit);
}

In the above example, the for...of loop iterates over each element in the fruits array. On each iteration, the current element is assigned to the variable fruit, and the code block console.log(fruit) is executed. The loop continues until all elements in the array have been processed.

Loops are fundamental in programming as they allow you to iterate over data, perform operations, and control the flow of your program. They provide powerful tools for automating repetitive tasks and handling complex scenarios.

Conclusion

In conclusion, this beginner's guide to JavaScript basics has provided you with a solid foundation for understanding syntax, variables, operators, control flow, and loops. By grasping these concepts, you're ready to write simple JavaScript code and go deeper in your learning.

Once you have familiarized yourself with these fundamental concepts, it is crucial that you embrace more intricate aspects of JavaScript in order to strengthen your comprehension of the language.

Note: mastering the basics is just the start. Consistently practice, experiment, and seek further resources to expand your knowledge.

As you continue your JavaScript journey, write clean code, follow best practices, and seek resources for growth. With dedication, you'll become a proficient JavaScript developer, unleashing creativity in building interactive web applications.

Embrace JavaScript's power and enjoy the coding journey ahead!

If you found this guide helpful and enjoyable, please give it a like🙏

More from this blog

Cas blog

9 posts