Learn the Basics of JavaScript with Code Examples

Learn the Basics of JavaScript with Code Examples

The console in JavaScript?

The console in JavaScript is a tool used for debugging and testing purposes. It allows developers to log information to the browser console for viewing. This can be useful for checking the values of variables, examining the output of functions, and tracking down errors in code.

There are several methods to log information to the console in JavaScript:

console.log(): This method logs the specified data to the console.?

For example:

console.log("Hello World"); // Output: Hello World

console.error(): This method logs an error message to the console.?

For example:

console.error("This is an error"); // Output: Error: This is an error


console.warn(): This method logs a warning message to the console.?

For example:

console.warn("This is a warning"); // Output: Warning: This is a warning


These methods can be used directly in the JavaScript code and the output can be viewed in the browser console by opening the Developer Tools in most modern browsers.


Here are some basics of JavaScript with code examples:


Variables:?

variables are used to store values in JavaScript. You can declare a variable with the "let" keyword, like this:

let x = 10;

let name = "John";

let age = 30;

let isStudent = false;

let weight = 75.5;

let address = "123 Main St.";

JavaScript variables are containers that store data values. There are three main types of variables in JavaScript:


var: This is the original way to declare a variable in JavaScript. It is function scoped, which means it is accessible within the function it was declared in.?


For example:

var name = "John";

function printName() {

??console.log(name);

}

printName(); // Output: John


let: This type of variable was introduced in ECMAScript 6 and is block scoped. It means that the variable is only accessible within the block of code it was declared in.?


For example:

let age = 30;

if (true) {

??let age = 40;

??console.log(age); // Output: 40

}

console.log(age); // Output: 30


const: This type of variable is also block scoped and was introduced in ECMAScript 6. The difference between const and let is that const cannot be reassigned after it has been declared.?


For example:

const country = "USA";

country = "Canada"; // Throws an error


It is important to note that the value stored inside a variable declared with const can still be mutable, meaning its properties can be changed but it cannot be reassigned to a completely new value.

JavaScript Comments

In JavaScript, you can add comments in your code to describe what it does or to temporarily ignore parts of the code. There are two types of comments: single-line comments and multi-line comments.


Single-line comment:

// This is a single-line comment

Multi-line comment:

/*?

??This is a multi-line?

??comment

*/


Here's an example that shows how comments can be used in a code:

// This is a single-line comment

/*?

??This is a multi-line?

??comment

*/


const name = "John"; // This is also a single-line comment

// The code below will print the value of the variable "name"

console.log(name);?


Data Types:

?JavaScript has several data types, including numbers, strings, and booleans. Here's an example of each:

let num = 10;

let str = "Hello World";

let bool = true;

let num1 = 20;

let num2 = -10;

let str1 = "Hello";

let str2 = 'JavaScript';

let bool1 = true;

let bool2 = false;



JavaScript Data Types

In JavaScript, there are seven basic data types:


Number: Used to represent numbers. Example: const num = 42;


String: Used to represent a sequence of characters. Example: const name = "John";


Boolean: Used to represent a logical value of either true or false. Example: const isMarried = true;


Undefined: Represents a value that has not been assigned. Example: const age; console.log(age); // Output: undefined


Null: Represents a value that is explicitly null. Example: const address = null;


Symbol: Used to create unique identifiers for objects. Example: const symbol = Symbol("description");


Object: Used to represent a collection of key-value pairs. Example: const person = { name: "John", age: 30 };


In JavaScript, variables have a dynamic type and can change their type based on the value assigned to them. The typeof operator can be used to check the type of a variable.


Example:

const num = 42;

console.log(typeof num); // Output: "number"


const name = "John";

console.log(typeof name); // Output: "string"


const isMarried = true;

console.log(typeof isMarried); // Output: "boolean"


const age;

console.log(typeof age); // Output: "undefined"


const address = null;

console.log(typeof address); // Output: "object"


const symbol = Symbol("description");

console.log(typeof symbol); // Output: "symbol"


const person = { name: "John", age: 30 };

console.log(typeof person); // Output: "object"

Arithmetic Operations:?

JavaScript supports basic arithmetic operations like addition, subtraction, multiplication, and division. Here's an example:

let x = 10;

let y = 5;

let sum = x + y;

let difference = x - y;

let product = x * y;

let quotient = x / y;

let x = 10;

let y = 20;

let sum = x + y;

let difference = x - y;

let product = x * y;

let quotient = x / y;

let modulo = x % y;

let increment = x++;

let decrement = y--;



Conditional Statements:?

Conditional statements are used to execute different blocks of code based on conditions. The if-else statement is the most common type of conditional statement in JavaScript. Here's an example:

let x = 10;

if (x > 5) {

??console.log("x is greater than 5");

} else {

??console.log("x is not greater than 5");

}

let grade = 85;


if (grade >= 90) {

??console.log("A");

} else if (grade >= 80) {

??console.log("B");

} else if (grade >= 70) {

??console.log("C");

} else {

??console.log("F");

}


let day = "Sunday";


switch (day) {

??case "Monday":

????console.log("Today is Monday");

????break;

??case "Tuesday":

????console.log("Today is Tuesday");

????break;

??case "Wednesday":

????console.log("Today is Wednesday");

????break;

??case "Thursday":

????console.log("Today is Thursday");

????break;

??case "Friday":

????console.log("Today is Friday");

????break;

??case "Saturday":

????console.log("Today is Saturday");

????break;

??default:

????console.log("Today is Sunday");

}



Functions:?

Functions are blocks of code that can be executed when they are called. Here's an example:

function greeting() {

??console.log("Hello World");

}


greeting();

function add(x, y) {

??return x + y;

}


let result = add(10, 20);

console.log(result);


function greet(name) {

??console.log("Hello " + name);

}


greet("John");


function calculateArea(width, height) {

??return width * height;

}


let area = calculateArea(10, 20);

console.log(area);


function checkOddEven(num) {

??if (num % 2 === 0) {

????return "Even";

??} else {

????return "Odd";

??}

}


let result = checkOddEven(10);

console.log(result);


function generateRandomNumber() {

??return Math.floor(Math.random() * 100);

}


let randomNumber = generateRandomNumber();

console.log(randomNumber);


These are just some of the basics of JavaScript. There is much more to learn, but these basics will give you a good foundation to start building your skills.


JavaScript Loops:

JavaScript has two types of loops: for loops and while loops. Here are examples of each:


For Loop:

for (const i = 0; i < 5; i++) {

??console.log("Iteration " + (i + 1));

}


This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5


While Loop:

const i = 0;

while (i < 5) {

??console.log("Iteration " + (i + 1));

??i++;

}


This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5


In addition to these two loops, there is also the do-while loop, which is similar to the while loop, but with a slight difference in the way the condition is checked. Here's an example:


const i = 0;

do {

??console.log("Iteration " + (i + 1));

??i++;

} while (i < 5);


This code will output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5


These are the basics of JavaScript loops. You can use them to repeat a block of code multiple times based on conditions.



JavaScript Arrays

An array in JavaScript is a data structure that stores a collection of values. You can access individual values of an array by referring to their index number. Arrays are declared using square brackets [] and items are separated by commas.


Here's an example of an array in JavaScript:

const fruits = ["apple", "banana", "cherry"];


JavaScript provides several built-in methods for working with arrays. Here are some commonly used methods with examples:


length property: returns the number of elements in an array.

const fruits = ["apple", "banana", "cherry"];

console.log(fruits.length); // Output: 3


push() method: adds an element to the end of an array.

const fruits = ["apple", "banana", "cherry"];

fruits.push("orange");

console.log(fruits); // Output: ["apple", "banana", "cherry", "orange"]


pop() method: removes the last element from an array and returns it.

const fruits = ["apple", "banana", "cherry"];

const lastFruit = fruits.pop();

console.log(fruits); // Output: ["apple", "banana"]

console.log(lastFruit); // Output: "cherry"


unshift() method: adds an element to the beginning of an array.

const fruits = ["apple", "banana", "cherry"];

fruits.unshift("peach");

console.log(fruits); // Output: ["peach", "apple", "banana", "cherry"]


shift() method: removes the first element from an array and returns it.

const fruits = ["apple", "banana", "cherry"];

const firstFruit = fruits.shift();

console.log(fruits); // Output: ["banana", "cherry"]

console.log(firstFruit); // Output: "apple"


splice() method: adds or removes elements from an array.

const fruits = ["apple", "banana", "cherry"];

fruits.splice(1, 0, "lemon", "lime");

console.log(fruits); // Output: ["apple", "lemon", "lime", "banana", "cherry"]

These are some of the most commonly used array methods in JavaScript. You can use these methods to manipulate arrays and perform various operations on them.

Complete Guide with PDF download at https://basescripts.com/basics-of-javascript-pdf-guide-for-beginners-with-code-examples

要查看或添加评论,请登录

Laurence Svekis ?的更多文章

社区洞察

其他会员也浏览了