Open In App

Getting Started with JavaScript

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is a lightweight, single-threaded, dynamically typed, interpreted programming language with object-oriented capabilities. Primarily JavaScript is used to add interactivity and dynamism to web pages. It breathes life into static HTML and CSS, enabling features like dynamic content updates, user interactions, and animations.

However, JavaScript’s reach extends beyond web development. It’s also employed in server-side development with frameworks like Node.js and for creating mobile applications through frameworks like React Native. In this article, we will go through the fundamentals of JavaScript.

Pre-requisites

Basics of JavaScript

Variables: Storing Information Like a Box

Imagine having boxes to hold different things. In JavaScript, variables act like these boxes, allowing you to store and manage information. A variable is a named container that holds a value, which can be text, numbers, or even collections of data. Declare variables using let, const, or var (though const and let are generally preferred for modern JavaScript):

Syntax:

let name = "Bob";
const age = 25; // Unchangeable value

let is the keyword that tells JavaScript you’re declaring a variable. where the message is the name of that variable. = is the assign operator that tells JavaScript to assign the value “Bob” string or 25 to the variable.

Data Types

Just like boxes can hold different items, variables in JavaScript can store various data types. Understanding these types is crucial. Data types categorize the information a variable can hold.

Common types in JavaScript:

  • Numbers: Integer (whole numbers) and floating-point (decimals) values (e.g., 10, 3.14).
  • Strings: Text enclosed in single or double quotes (e.g., “Geeksforgeeks”, ‘Hello World’).
  • Booleans: Represent logical values, true and false.
  • Undefined: Represents a variable that has been declared but not assigned a value.
  • Null: Represents the intentional absence of a value.
  • Objects: Complex data structures that store key-value pairs (e.g., const person = { name: “Alice”, age: 30 }).
  • Arrays: Ordered lists of values, accessed using zero-based indexes (e.g., const colors = [“red”, “green”, “blue”]).

Operators: Performing Actions on Your Data

Think of operators as tools you use to manipulate the data inside your variables. JavaScript offers various operators for performing calculations, comparisons, and more. Operators allow you to perform operations on data.

Some basic operators in JavaScript:

  • Arithmetic: +, -, *, /, % (modulo)
  • Assignment: =, +=, -=, *=, /=, etc.
  • Comparison: ==, !=, ===, !==, <, >, <=, >=
  • Logical: && (AND), || (OR), ! (NOT)
  • Increment/Decrement: ++, —
  • Conditional (Ternary): condition ? expressionIfTrue : expressionIfFalse

Control Flow Statements and Loops

Control flow statements determine the execution flow of your code:

  • if…else: Executes code blocks conditionally based on a Boolean expression.
  • switch: Executes different code blocks based on a matching case value.

Loops are used to execute a block of code repeatedly until a certain condition is met. JavaScript offers several looping constructs:

  • for loop: Executes code a specified number of times, often used with counters.
  • while loop: Executes code as long as a condition is true.
  • do while loop : Similar to while, but the code block always executes at least once.

Functions

Functions are reusable blocks of code that perform specific tasks. They can take input (arguments) and return output (values).

Arrow Functions: A concise syntax for defining functions, introduced in ES6 (ECMAScript 2015).

Arrays

Ordered collections of values, accessed using zero-based indexes. Useful for storing lists of items.

Objects

Complex data structures that store key-value pairs, allowing you to organize related data efficiently.

Comments

Comments are lines of text ignored by the interpreter and used to explain or document code.

Syntax:

// Single-line comment
/* Multi-line comment */

Hoisting

A JavaScript behaviour where function declarations are moved to the top of their scope (typically the script) before code execution. This means you can call a function before it’s declared in the code. However, this is generally considered bad practice as it can lead to unexpected behaviour in modern JavaScript.

DOM Manipulation

JavaScript can interact with the Document Object Model (DOM), allowing you to dynamically modify the content and structure of your web pages. This opens doors for creating interactive elements, updating content based on user input, and building dynamic web applications.

Event Handling

JavaScript can listen for events like button clicks, mouse movements, and keyboard presses, enabling user interaction and responsiveness. By handling these events, you can trigger specific actions like updating content, displaying messages, or performing calculations based on user input.

Steps to Run the JavaScript Code

Here are two common ways to run JavaScript code:

Using JavaScript in a web project:

Using the browser console: Most web browsers come with a built-in console where you can directly execute JavaScript code. Open your browser’s developer tools (usually by pressing F12) and look for the console tab. You can then type your JavaScript code and press Enter to see the output.

Creating an HTML file: You can create a simple HTML file with a <script> tag to embed your JavaScript code. The browser will interpret the code when the webpage loads.

Here’s a basic example:

<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Code</title>
</head>
<body>
<script>
let message = "Hello from my HTML file!";
console.log(message);
</script>
</body>
</html>

Save this code as an HTML file (e.g., index.html) and open it in your browser. You won’t see any direct changes on the webpage, but you can access the console to see the output: “Hello from my HTML file!” or you can get the same result my adding external javascript to the script tag in HTML.

Using JavaScript outside the browser (Node.js)

Step 1: Node.js environment: If your project involves running JavaScript code outside a web browser, you can leverage Node.js. Node.js is a JavaScript runtime environment that allows you to execute JavaScript code on your computer.

Step 2: Create JavaScript files: Similar to web development, you’ll create JavaScript files (.js extension) containing your code.

Step 3: Run JavaScript code: You can run JavaScript code using the Node.js command line or integrate it into your project using Node.js modules.

Example: Here’s a simple JavaScript program that logs a message to the browser console:

Console.log("GeeksforGeeks");

Output: When you run this code in a browser’s developer console or an appropriate JavaScript execution environment, it will display:

GeeksforGeeks

Advantages of Using JavaScript

  • Versatility: JavaScript is not limited to web development. It can be used for creating server-side applications (using Node.js), mobile app development (with frameworks like React Native), and even game development.
  • Ease of Use: Compared to other programming languages, JavaScript has a relatively simpler syntax, making it easier to learn, especially for beginners.
  • Interactivity: JavaScript enables dynamic and interactive elements on web pages, enhancing user experience significantly.
  • Large Community and Resources: With its widespread adoption, JavaScript boasts a vast and supportive community of developers

How to use JavaScript in a Project

Using JavaScript in a project can vary depending on the type of project you’re working on and your specific requirements. JavaScript’s application depends on your project’s environment. Here’s a breakdown for the most common scenarios:

Using JavaScript in a Web Project:

Internal JavaScript:

Include the JavaScript code directly within your HTML file using the <script> tag. Place the <script> tag either inside the <head> section (for code to run before page load) or at the end of the <body> section (for code to run after the page loads).

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Internal JavaScript Example</title>
    <script>
        function greet() {
            alert("Hello from Internal JavaScript! and Welcome To GFG");
        }
    </script>
</head>

<body>
    <button onclick="greet()">Click me</button>
</body>

</html>

Open the HTML file in a web browser. The embedded JavaScript code will be executed when the page loads or when the corresponding event (like a button click) occurs.

External JavaScript:

Create a new file with a .js extension (e.g., myscript.js). Write your JavaScript code within this file. Include a <script> tag within your HTML file, but this time with the “src” attribute specifying the path to your external JavaScript file.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>External JavaScript Example</title>
    <script src="myscript.js"></script>
</head>

<body>
    <button onclick="greet()">Click me</button>
</body>

</html>
Javascript
function greet() {
  alert("Hello from External JavaScript! and Welcome to GFG");
}

Open the HTML file in a web browser. The external JavaScript file will be loaded and executed when the page loads.

Using JavaScript with Node.js (Backend):

Download and install Node.js from the official website https://nodejs.org/en

Similar to external JavaScript for web, create a file with a .js extension (e.g., app.js). Write your JavaScript code in this file, but here you can leverage Node.js functionalities like file system access, server creation, database interactions, etc.

Open a terminal or command prompt and navigate to the directory containing your JavaScript file. Run the following command to execute the JavaScript code using Node.js:

node app.js

This will run the code within the Node.js environment, typically used for server-side operations.

However, here are some general steps to guide you through after integrating JavaScript into your project:

  • Debugging: Use browser developer tools (e.g., Chrome DevTools, Firefox Developer Tools) to debug your JavaScript code. These tools provide features like breakpoints, console logging, and inspection of variables to help you identify and fix issues in your code.
  • Package management and dependencies (optional): If your project requires external libraries or dependencies, you can use tools like npm (Node Package Manager) or yarn to manage them. You can install packages using npm or yarn and then import them into your JavaScript files as needed.
  • Version control (optional): If you’re working in a team or want to maintain a version history of your project, consider using version control systems like Git. You can initialize a Git repository in your project directory, commit your changes, and collaborate with others more effectively.
  • Testing and optimization (optional): Depending on the complexity of your project, you may want to implement testing frameworks (e.g., Jest for unit testing) and optimization techniques (e.g., code minification, performance tuning) to ensure your JavaScript code is efficient and reliable.

By following these steps, you can effectively integrate JavaScript into your project and leverage its capabilities to build interactive and dynamic web applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads