0% found this document useful (0 votes)
4 views

Java Sp Crit

This document serves as a comprehensive introduction to JavaScript, covering its definition, capabilities, execution environments, and its relationship with ECMAScript. It includes practical guidance on writing JavaScript code, setting up a development environment, and understanding core concepts such as variables, data types, functions, and object manipulation. Additionally, it emphasizes best practices for structuring code and provides examples for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Sp Crit

This document serves as a comprehensive introduction to JavaScript, covering its definition, capabilities, execution environments, and its relationship with ECMAScript. It includes practical guidance on writing JavaScript code, setting up a development environment, and understanding core concepts such as variables, data types, functions, and object manipulation. Additionally, it emphasizes best practices for structuring code and provides examples for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Created by Turbolearn AI

Introduction to JavaScript
This study guide covers the fundamentals of JavaScript, including its definition,
capabilities, execution environments, and relationship to ECMAScript.

What is JavaScript?
JavaScript is a popular and widely used programming language.
It's one of the fastest-growing languages, used by major companies like Netflix,
Walmart, and PayPal.
The average salary of a JavaScript developer in the United States is $72,000
per year.
Roles include:
Front-end developer
Back-end developer
Full-stack developer

What Can You Do With JavaScript?


Originally used for interactive web pages in browsers.
Now used for:
Full-blown web and mobile applications
Real-time networking applications (chats, video streaming)
Command-line tools
Games

Where Does JavaScript Code Run?


JavaScript was initially designed to run in browsers.
Browsers have JavaScript engines to execute JavaScript code (e.g.,
SpiderMonkey in Firefox, V8 in Chrome).
Node.js: Ryan Dahl embedded Chrome's V8 engine in a C++ program, allowing
JavaScript to run outside the browser.
Node.js enables JavaScript to build the backend for web and mobile
applications.
JavaScript can run inside a browser or in Node.
Browsers and Node provide a runtime environment for JavaScript code.

JavaScript vs. ECMAScript

Page 1
Created by Turbolearn AI

ECMAScript is a specification, while JavaScript is a programming language that


conforms to this specification.
ECMA is the organization responsible for defining standards (including
ECMAScript).
First version of ECMAScript released in 1997.
Since 2015, ECMA releases annual updates to the specification.
ECMAScript 2015 (ES6) introduced many new features to JavaScript.

Writing First JavaScript Code

Opening the Console


1. Open Chrome.
2. Right-click on an empty area and select "Inspect."
3. Select the "Console" tab in Chrome Developer Tools.

Basic JavaScript Example

console.log('Hello world');

This line logs the message "Hello world" to the console.

alert('Yo');

This code creates a pop-up alert in the browser.

Setting Up Your Development Environment

Code Editors

Page 2
Created by Turbolearn AI

Various code editors are available, including:


Visual Studio Code (VS Code)
Sublime Text
Atom
Visual Studio Code is recommended:
Download from code.visualstudio.com.
Lightweight, cross-platform, and powerful.

Node.js
Download Node.js from nodejs.org.
While not strictly necessary for executing JavaScript (as browsers can do this),
Node.js is useful for:
Installing third-party libraries.
Backend development.

Project Setup
1. Create a new folder (e.g., js-basics).
2. Open the folder in Visual Studio Code.
3. Add a new file: index.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Basics</title>
</head>
<body>
<h1>Hello World</h1>
<script>
console.log('Hello world');
</script>
</body>
</html>

Type ! and press Tab to generate basic HTML boilerplate.

Page 3
Created by Turbolearn AI

Live Server Extension


1. Install the "Live Server" extension in Visual Studio Code.
2. Restart Visual Studio Code after installation.
3. Right-click index.html and select "Open with Live Server."
This will open the HTML file in your browser and automatically refresh on
changes.

To verify setup, add an <h1> tag in the body:

<h1>Hello World</h1>

Save the changes, and the browser should automatically refresh, displaying "Hello
World."

Writing JavaScript in HTML

Script Element
JavaScript code is placed inside <script> elements.
The best practice is to put the <script> element at the end of the <body>
section.
This ensures that all HTML elements are rendered before the JavaScript
code runs.
Avoids blocking page rendering while the browser parses and executes
JavaScript.
Ensures that JavaScript code can interact with all elements on the page.

Statements
A statement is a piece of code that expresses an action to be carried out.
All statements in JavaScript should be terminated by a semicolon.

Strings

Page 4
Created by Turbolearn AI

A string is a sequence of characters.

Comments

// This is a comment. It is ignored by the JavaScript engine.

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

JavaScript Engine and Code Documentation


In JavaScript, comments are used to document code. These comments are not
executed by the JavaScript engine but serve to explain the code to other developers,
focusing on the "why" and "how" rather than the "what."

Example:

// This is my first JavaScript code


console.log("Hello, world!");

Separation of Concerns: Structuring JavaScript


Code
In real-world applications, JavaScript code should be separated from HTML to
maintain a clean structure, mirroring the organization in your house where you don't
store clothes in the kitchen.

Separation of Concerns: Separating HTML (content) from JavaScript


(behavior) ensures that the structure and content of a webpage are
distinct from its interactive elements. HTML handles content, while
JavaScript handles behavior, such as what happens when a mouse hovers
over an element.

To implement this separation:

Page 5
Created by Turbolearn AI

1. Create a new file (e.g., index.js) to house JavaScript code.

2. Move the JavaScript code from the <script> element in your HTML file to the
new .js file.

3. Reference the .js file in your HTML using the src attribute in the <script> tag:

<script src="index.js"></script>

Executing JavaScript Code in Node.js


Node.js is a runtime environment that allows you to execute JavaScript code outside
of a browser. It uses Google's V8 JavaScript engine to run the code.

Steps to Execute JavaScript in Node.js:


1. Install Node.js: Download the latest version from nodejs.org.

2. Open Terminal/Command Prompt: Navigate to the directory containing your


JavaScript file.

3. Run the Code: Execute the JavaScript file using the command:

node index.js

VS Code Integrated Terminal


VS Code has an integrated terminal that you can open via the View menu or using a
shortcut. This terminal is useful for running Node.js commands without leaving the
editor.

Variables: Storing Data in Memory

Page 6
Created by Turbolearn AI

Variables are used to store data temporarily in a computer's memory. They are like
boxes with labels, where the label is the variable name, and the contents of the box
are the value assigned to the variable.

Declaring and Initializing Variables


In modern JavaScript (ES6+), it's best practice to use the let keyword to declare
variables:

let name; // Declaring a variable


console.log(name); // Output: undefined

name = "Marsh"; // Initializing the variable


console.log(name); // Output: Marsh

Rules for Naming Variables

Rule Description Example

Cannot be a
Variables cannot be named after JavaScript reserved Invalid: let
reserved
keywords like let, if, else, or var. if;
keyword
Should be Variable names should clearly indicate the purpose of Good:
meaningful the variable. firstName;
Cannot start with Invalid:
Variable names cannot begin with a numeric character.
a number 1name;
Use camel case notation for multiple words. The first
Cannot contain a letter of the first word should be lowercase, and the Good:
space or hyphen first letter of each subsequent word should be firstName;
uppercase.
JavaScript variable names are case-sensitive, meaning
Case-sensitive name != Name
name and Name are treated as different variables.

Camel Case Notation

Page 7
Created by Turbolearn AI

Camel Case Notation: Writing variable names where the first word is
lowercase, and each subsequent word starts with a capital letter.

Example:

Page 8
Created by Turbolearn AI

let firstName = "John";


```## Variables in JavaScript

Here's what you need to know about variables in JavaScript:

* In JavaScript, `firstName` and `FirstName` are different variables, bu


* You can declare multiple variables on one line separated by commas, bu

```js
let firstName;
let lastName;
```

## Constants

* Constants are declared using `const`. Their values cannot be changed a


* If you try to reassign a value to a constant, you'll get a `TypeError`
* Use `const` by default, unless you need to reassign the variable.

```js
const interestRate = 0.3;
interestRate = 1; // This will cause an error
```

## Data Types

JavaScript has two categories of data types:

* **Primitives (Value Types)**


* **Reference Types**

Let's explore primitive types:

* **String:** A sequence of characters.

```js
let name = 'Mosh'; // String literal
```
* **Number:** Numeric values.

```js
let age = 30; // Number literal
```
* **Boolean:** `true` or `false`.

```js
let isApproved = true; // Boolean literal
```
* **Undefined:** Represents a variable that has not been assigned a valu

```js
let firstName; // Value is undefined by default
let lastName = undefined; //Explicitly assigned undefined
```
* **Null:** Represents the intentional absence of a value.

Page 9
Created by Turbolearn AI

```js
let selectedColor = null; // Used to clear the value of a variable
```

## Dynamic Typing

JavaScript is a dynamic language, meaning the type of a variable can chang

```js
let name = 'Mosh'; // Type is string
name = 30; // Type is now number

You can use the typeof operator to check the type of a variable:

typeof name;

Even if you change a number to a floating-point number, its type remains number:

let age = 30.1;


typeof age; // Returns "number"

Here's a summary table of the primitive types we discussed:

Type Description Example

String Sequence of characters 'Mosh'


Number Numeric value (integers and floating-point) 30, 30.1
Boolean true or false true, false
Undefined Variable has not been assigned a value let firstName;
Null Intentional absence of a value let selectedColor = null;

Reference Types
There are three key reference types:

Objects
Arrays
Functions

Page 10
Created by Turbolearn AI

Objects
An object in JavaScript is a collection of key-value pairs, representing
properties and methods.

When dealing with multiple related variables, you can group them inside an object.
Instead of declaring separate variables, you can declare a single person object and
reference its properties.

Object Literals in JavaScript


If you don't want to reassign the person object, you can set it to an object literal.

Object Literal: Syntax using curly braces {} to define an object. Inside the
braces, you add one or more key-value pairs, where keys are the
properties of the object.

Example:

let person = {
name: "Maash",
age: 30
};
console.log(person);

Accessing Object Properties


There are two ways to access properties in JavaScript:

Dot Notation
Bracket Notation

Dot Notation
The dot notation is a way to access an object's properties by using a dot (.) followed
by the property name.

Example:

Page 11
Created by Turbolearn AI

person.name = "John";
console.log(person.name); // Output: John

Bracket Notation
The bracket notation uses square brackets [] with a string inside to specify the
property name.

Example:

person["name"] = "Mary";
console.log(person["name"]); // Output: Mary

Dot Notation vs. Bracket Notation

Feature Dot Notation Bracket Notation

Syntax object.property object["property"]


Use Cases Simpler, more concise Dynamic property access, runtime determination
Readability Generally preferred Less readable when property name is static

When to use Bracket Notation:

When the property name is not known until runtime.


When the property name is stored in a variable.

Example:

let selection = "name";


console.log(person[selection]); // Accessing property dynamically

Arrays in JavaScript
Arrays are used to store lists of objects.

Page 12
Created by Turbolearn AI

Example:

let selectedColors = []; // Empty array


selectedColors = ['red', 'blue'];
console.log(selectedColors); // Output: ['red', 'blue']

Array Elements and Indices


Each element in an array has an index, which determines its position. The index of the
first element is 0.

Example:

console.log(selectedColors[0]); // Output: red

Dynamic Nature of Arrays


JavaScript is a dynamic language, meaning the types of variables can change at
runtime. This also applies to arrays:

The length of an array can change.


The types of objects in an array can be different.

Example:

selectedColors[2] = 'green';
selectedColors[3] = 10;
console.log(selectedColors); // Output: ['red', 'blue', 'green', 10]

Arrays as Objects
Arrays in JavaScript are technically objects. Each array has a set of key-value pairs or
properties that can be accessed using dot notation.

Page 13
Created by Turbolearn AI

Example:

console.log(typeof selectedColors); // Output: object


console.log(selectedColors.length); // Output: 4

Length Property
The length property of an array returns the number of elements in the array.

Functions in JavaScript
Function: A set of statements that performs a task or calculates a value.

Example:

function greet() {
console.log('hello world');
}

greet(); // Calling the function

Function Parameters
Functions can have inputs called parameters, which can change the behavior of the
function.

Example:

Page 14
Created by Turbolearn AI

function greet(name) {
console.log('Hello ' + name);
}
```## Functions in JavaScript

### Function Parameters and Arguments

When defining a function, you can specify **parameters**, which act as pla

> A **parameter** is a variable listed inside the parentheses in the funct

For example:

```js
function greet(name) {
console.log("Hello " + name);
}

In the greet function, name is a parameter. It is only meaningful inside this function,
and is not accessible outside of it.

When you call a function, you provide arguments, which are the actual values that
are passed to the function's parameters.

An argument is the actual value that is passed to a function when it is


called.

For example:

greet("John");

In this case, "John" is an argument to the greet function.

A function can have multiple parameters, separated by commas:

function greet(firstName, lastName) {


console.log("Hello " + firstName + " " + lastName);
}

greet("John", "Smith"); // Output: Hello John Smith

Page 15
Created by Turbolearn AI

If you don't provide an argument for a parameter, its value defaults to undefined.

Function Tasks vs. Calculations


Functions can either perform a task or calculate and return a value.

Performing a Task
A function that performs a task typically executes a series of statements to achieve a
specific outcome, such as displaying something on the console.

Example:

function greet(name) {
console.log("Hello " + name);
}

Calculating a Value
A function that calculates a value performs a computation and returns the result. The
return keyword is used to send the calculated value back to the caller.

Example:

function square(number) {
return number * number;
}

let result = square(2);


console.log(result); // Output: 4

In this case, the square function calculates the square of a number and returns the
result.

Function Calls

Page 16
Created by Turbolearn AI

When you use a function in javascript, there will always be a function call. Even
something that looks simple, like:

console.log("Hello");

Is a function call. Here, we are calling the log function which is defined somewhere
else, and passing it the argument "Hello". Similarly:

console.log(square(2));

Here, square(2) is a function call, and console.log() is also a function call.

Real-World Applications
A real-world application is essentially a collection of hundreds or thousands of
functions working together to provide the functionality of that application.

Page 17

You might also like