JavaScript Basics : A Detailed Guide

Get started with JavaScript Basics at Edulane. Learn about JavaScript Introduction, Setting up the development environment (Node.js, VS Code), Comments, and essential syntax, to kickstart your coding journey.

Table of contents

What is Javascript

JavaScript is a high-level, interpreted programming language that is widely used to create interactive effects within web browsers. It is one of the core technologies of the World Wide Web, alongside HTML and CSS. Here are some key aspects of JavaScript:

  1. Client-Side Scripting: JavaScript is primarily known for its role in client-side scripting. It allows developers to create dynamic and interactive web pages by manipulating the Document Object Model (DOM), handling events, and performing asynchronous operations.
  2. Server-Side Programming: JavaScript can also be used on the server side through environments like Node.js, enabling full-stack development with a single programming language.
  3. Versatility: JavaScript can be used for a variety of applications, from simple form validations to complex single-page applications (SPAs) and mobile app development using frameworks like React Native.
  4. Libraries and Frameworks: JavaScript has a rich ecosystem of libraries and frameworks such as React, Angular, Vue.js, jQuery, and many others that simplify and enhance web development.
  5. Event-Driven and Asynchronous: JavaScript is event-driven, meaning it can respond to user interactions and other events. It also supports asynchronous programming, which is crucial for handling operations like API calls without freezing the user interface.
  6. Prototypal Inheritance: JavaScript uses prototypal inheritance, which is different from the classical inheritance model found in languages like Java and C++.
  7. Standardization: JavaScript is standardized under the ECMAScript (ES) specification. Over the years, many versions of ECMAScript have been released, with ES6 (ECMAScript 2015) being one of the most significant updates, introducing features like classes, modules, arrow functions, and more.
  8. Integration: JavaScript can be easily integrated with other technologies and APIs, making it a versatile choice for web development.

Overall, JavaScript is a powerful and flexible language that plays a crucial role in modern web development.

JavaScript engine

JavaScript engines are programs that execute JavaScript code. They are responsible for parsing, interpreting, compiling, and running JavaScript. Different browsers and environments use different JavaScript engines. Here are some of the most well-known types of JavaScript engines:

  1. V8:
    • Developed by Google.
    • Used in Google Chrome and Node.js.
    • Known for its performance and efficiency.
  2. SpiderMonkey:
    • Developed by Mozilla.
    • Used in the Firefox browser.
    • The first ever JavaScript engine, created by Brendan Eich in 1995.
  3. JavaScriptCore (Nitro):
    • Developed by Apple.
    • Used in Safari and other WebKit-based browsers.
    • Focuses on performance and security.
  4. Chakra:
    • Developed by Microsoft.
    • Used in the Microsoft Edge browser (legacy version).
    • Known for its performance in the EdgeHTML engine.
  5. ChakraCore:
    • An open-source version of the Chakra engine.
    • Used in a variety of applications beyond the browser.
  6. Hermes:
    • Developed by Facebook.
    • Used in React Native applications.
    • Optimized for running JavaScript on mobile devices.

Each of these engines has its own optimizations and features, making them suitable for different environments and use cases.

Setting up the development environment (Node.js, VS Code)

Setting up a development environment for JavaScript using Node.js and Visual Studio Code (VS Code) involves several steps. Here is a detailed guide:

Step 1: Install Node.js and npm
  1. Download Node.js:
    • Visit the official Node.js website.
    • Download the latest LTS (Long Term Support) version, as it is more stable.
    • The download will include both Node.js and npm (Node Package Manager).
  2. Install Node.js:
    • Run the installer you downloaded.
    • Follow the installation prompts. You can generally accept the default options.
    • Verify the installation by opening a terminal (Command Prompt on Windows, Terminal on macOS/Linux) and typing:
node -v
npm -v
  • You should see version numbers for both Node.js and npm.
Step 2: Install Visual Studio Code (VS Code)
  1. Download VS Code:
  2. Install VS Code:
    • Run the installer you downloaded.
    • Follow the installation prompts, accepting the default options.
    • Once installed, launch VS Code.
Step 3: Configure VS Code for JavaScript Development
  1. Open a New Folder:
    • In VS Code, go to File > Open Folder... and select or create a new folder for your JavaScript projects.
  2. Install Extensions:
    • Open the Extensions view by clicking the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X (Cmd+Shift+X on macOS).
    • Install the following recommended extensions:
      • ESLint: For linting JavaScript code.
      • Prettier – Code Formatter: For consistent code formatting.
      • JavaScript (ES6) code snippets: Provides a collection of useful JavaScript snippets.
      • Node.js Modules Intellisense: Autocompletes Node.js modules in import statements.
      • Debugger for Chrome: If you want to debug your JavaScript code in Chrome.
Step 4: Create a Sample JavaScript Project
  • 1. Initialize a Node.js Project:
    • Open a terminal in VS Code by going to Terminal > New Terminal.
    • Navigate to your project folder (if not already there).
    • Initialize a new Node.js project with:
npm init -y
  • This command creates a package.json file with default settings.
  • 2. Install Dependencies:
    • If you need any specific packages for your project, you can install them using npm. For example, to install Express (a popular web framework), run:
npm install express
  • 3. Create Your JavaScript Files:
    • In your project folder, create a new file named index.js.
    • Open index.js and write a simple JavaScript code. For example:
Step 5: Run Your JavaScript Code
  1. Run in Terminal:
    • In the terminal, run your JavaScript file with:
node index.js
  • You should see the output Hello, Node.js! in the terminal.
Step 6: Configure Linting and Formatting
  1. Create Configuration Files:
    • Create an ESLint configuration file by running:
npx eslint --init
  • Follow the prompts to configure ESLint to your preferences.
  • Create a Prettier configuration file (optional):
    • Create a file named .prettierrc in the root of your project folder.
    • Add your preferred Prettier settings. For example.
{
  "singleQuote": true,
  "semi": false
}
  • 2. Enable Format on Save:
    • In VS Code, go to File > Preferences > Settings (or press Ctrl+,).
    • Search for format on save and check the box to enable it.
Step 7: Debugging with VS Code
  1. Set Up Launch Configuration:
    • Go to the Run and Debug view by clicking the Run icon in the Activity Bar or by pressing Ctrl+Shift+D (Cmd+Shift+D on macOS).
    • Click on create a launch.json file, then select Node.js.
    • A launch.json file will be created in the .vscode folder with a default configuration.
  2. Add Breakpoints and Start Debugging:
    • Open your index.js file, click in the gutter next to a line number to set a breakpoint.
    • Press F5 to start debugging. Your code will run and stop at the breakpoint, allowing you to inspect variables and step through your code.
Step 8: Using Git and GitHub (Optional but Recommended)
  • 1. Initialize Git:
    • In the terminal, navigate to your project folder and run:
git init
  • 2. Create a .gitignore File:
    • Create a file named .gitignore in your project folder.
    • Add files and folders to ignore. For example:
node_modules
.env
  • 3. Commit Your Code:
    • Add your files to the staging area and commit them:
git add .
git commit -m "Initial commit"
  • 4. Push to GitHub:
    • Create a new repository on GitHub.
    • Follow the instructions provided by GitHub to push your local repository to GitHub.
Conclusion

You’ve now set up a basic development environment for JavaScript using Node.js and VS Code. From here, you can start building and testing your JavaScript applications, leveraging the powerful tools and extensions provided by VS Code.

Writing your first JavaScript program

  • Write the JavaScript Code:
    • Open index.js and write the following code:
console.log('Hello, World!');
  • Run Your JavaScript Program
    • Run in Terminal
      • In the terminal, run your JavaScript file with:
node index.js
  • You should see the output Hello, World! in the terminal.

Basic syntax and comments

Understanding the basic syntax and how to use comments in JavaScript is crucial for writing clear and effective code. Let’s go through these concepts in detail.

Basic Syntax

Variables – Variables are used to store data. In JavaScript, you can declare variables using var, let, or const.

var firstName = 'John';  // Variable declared with var
let age = 30;      // Variable declared with let
const PI = 3.14;   // Constant variable declared with const

Data Types – JavaScript has several data types, including:

// String: Represents textual data.
let message = "Hello, World!";

// Number: Represents both integer and floating-point numbers.
let count = 42;
let temperature = 36.6;

// Boolean: Represents true or false.
let isActive = true;

// Array: Represents a list of elements.
let fruits = ['Apple', 'Banana', 'Cherry'];

// Object: Represents a collection of key-value pairs.
let person = {
    firstName: 'Alice',
    age: 25
};

// Null: Represents the intentional absence of any object value.
let emptyValue = null;
// Undefined: Represents an uninitialized variable.
let unknown;

// Operators - JavaScript supports various operators for performing operations on variables and values.
// Arithmetic Operators: +, -, *, /, %
let sum = 10 + 5;  // 15
let product = 4 * 2;  // 8
// Assignment Operators: =, +=, -=, *=, /=
let x = 10;
x += 5;  // x is now 15
// Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
let isEqual = (5 == '5');  // true
let isStrictEqual = (5 === '5');  // false
// Logical Operators: &&, ||, !
let isTrue = true && false;  // false
let isEitherTrue = true || false;  // true

// Functions - Functions are reusable blocks of code that perform a specific task.
function greet(name) {
    return 'Hello, ' + name + '!';
}

let message = greet('Alice');  // Hello, Alice!

// You can also define functions using arrow syntax:
const greet = (name) => {
    return 'Hello, ' + name + '!';
};
let message = greet('Bob');  // Hello, Bob!

// Please check other Day's lesson for understand all these Thanks :)

Comments

Comments are used to explain code and are ignored by the JavaScript engine.

Single-Line Comments

Single-line comments start with //.

// This is a single-line comment
let x = 10;  // This comment is on the same line as code
Multi-Line Comments

Multi-line comments start with /* and end with */.

/*
This is a multi-line comment.
It can span multiple lines.
*/
let y = 20;
  • Check the below examples and explanation you will understand why we should use comments in our code –

Writing clear and meaningful comments in your code/functions is crucial for maintaining and understanding your code. Here’s an example of a well-commented function that calculates the factorial of a number:

Factorial Function Example

/**
 * Calculate the factorial of a given number.
 *
 * The factorial of a non-negative integer n is the product of all
 * positive integers less than or equal to n. It is denoted by n!.
 * For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
 *
 * @param {number} n - A non-negative integer whose factorial is to be calculated.
 * @returns {number} The factorial of the given number. If n is 0, returns 1.
 * @throws {Error} Will throw an error if the input is a negative integer or not a number.
 */
function factorial(n) {
    // Check if the input is a non-negative integer
    if (typeof n !== 'number' || n < 0 || !Number.isInteger(n)) {
        throw new Error('Input must be a non-negative integer.');
    }

    // Base case: if n is 0, return 1 (as 0! is defined to be 1)
    if (n === 0) {
        return 1;
    }

    // Recursive case: n! = n * (n-1)!
    return n * factorial(n - 1);
}

// Example usage:
try {
    const result = factorial(5);  // Expected output: 120
    console.log('Factorial of 5 is:', result);
} catch (error) {
    console.error(error.message);
}

Explanation of Comments

  1. Function Description:
    • The function is described at the top using a block comment that explains what the function does, including a brief explanation of the factorial concept.
  2. Parameter Description:
    • The @param tag in the comment block describes the type and purpose of the input parameter n.
  3. Return Value:
    • The @returns tag describes the type and meaning of the value returned by the function.
  4. Error Handling:
    • The @throws tag explains the conditions under which the function will throw an error.
  5. Inline Comments:
    • Comments inside the function explain the logic, including the base case and the recursive case.
Key Points for Writing Comments
  • Descriptive and Concise: Comments should be clear and to the point, explaining the purpose and functionality without being verbose.
  • Consistent Style: Use a consistent style for comments, such as starting block comments with a brief description and using @param, @returns, and @throws tags for documentation.
  • Keep Code and Comments in Sync: Ensure that comments accurately describe the code and update them when the code changes.
  • Avoid Obvious Comments: Do not add comments that state the obvious or repeat what the code itself clearly indicates. For example, let x = 10; // Declare x as 10 is unnecessary.
More Examples
// Declare variables
let firstName = 'John';  // String variable
const age = 30;  // Constant number variable

// Function to greet a person
function greet(person) {
    // Return a greeting message
    return 'Hello, ' + person + '!';
}

// Call the function and store the result
let greetingMessage = greet(name);

// Output the result
console.log(greetingMessage);  // Output: Hello, John!

/* 
  This part demonstrates arithmetic operations.
  It calculates the sum and product of two numbers.
*/
let num1 = 10;
let num2 = 5;

let sum = num1 + num2;  // Sum: 15
let product = num1 * num2;  // Product: 50

// Log the results
console.log('Sum:', sum);  // Output: Sum: 15
console.log('Product:', product);  // Output: Product: 50

This example demonstrates variable declaration, function definition, arithmetic operations, and how to use both single-line and multi-line comments effectively.