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?
- Setting up the development environment (Node.js, VS Code)
- Writing your first JavaScript program
- Basic syntax and comments
- More Examples
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- Prototypal Inheritance: JavaScript uses prototypal inheritance, which is different from the classical inheritance model found in languages like Java and C++.
- 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.
- 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:
- V8:
- Developed by Google.
- Used in Google Chrome and Node.js.
- Known for its performance and efficiency.
- SpiderMonkey:
- Developed by Mozilla.
- Used in the Firefox browser.
- The first ever JavaScript engine, created by Brendan Eich in 1995.
- JavaScriptCore (Nitro):
- Developed by Apple.
- Used in Safari and other WebKit-based browsers.
- Focuses on performance and security.
- Chakra:
- Developed by Microsoft.
- Used in the Microsoft Edge browser (legacy version).
- Known for its performance in the EdgeHTML engine.
- ChakraCore:
- An open-source version of the Chakra engine.
- Used in a variety of applications beyond the browser.
- 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
- 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).
- 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)
- Download VS Code:
- Visit the official Visual Studio Code website.
- Download the version suitable for your operating system (Windows, macOS, or Linux).
- 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
- Open a New Folder:
- In VS Code, go to
File
>Open Folder...
and select or create a new folder for your JavaScript projects.
- In VS Code, go to
- 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.
- Open the Extensions view by clicking the Extensions icon in the Activity Bar on the side of the window or by pressing
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:
- Open a terminal in VS Code by going to
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:
- In your project folder, create a new file named
Step 5: Run Your JavaScript Code
- 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
- 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.
- Create a file named
{
"singleQuote": true,
"semi": false
}
- 2. Enable Format on Save:
- In VS Code, go to
File
>Preferences
>Settings
(or pressCtrl+,
). - Search for
format on save
and check the box to enable it.
- In VS Code, go to
Step 7: Debugging with VS Code
- 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 selectNode.js
. - A
launch.json
file will be created in the.vscode
folder with a default configuration.
- Go to the Run and Debug view by clicking the Run icon in the Activity Bar or by pressing
- 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.
- Open your
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:
- Create a file named
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:
- Open
console.log('Hello, World!');
- Run Your JavaScript Program
- Run in Terminal
- In the terminal, run your JavaScript file with:
- Run in Terminal
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
- 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.
- Parameter Description:
- The
@param
tag in the comment block describes the type and purpose of the input parametern
.
- The
- Return Value:
- The
@returns
tag describes the type and meaning of the value returned by the function.
- The
- Error Handling:
- The
@throws
tag explains the conditions under which the function will throw an error.
- The
- 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.