Introduction to JavaScript

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

In what year was JavaScript created?

  • 1990
  • 1995 (correct)
  • 2000
  • 2005

What is the primary use of client-side scripting in JavaScript?

  • Database administration
  • Improving web page responsiveness (correct)
  • Operating system development
  • Back-end server management

What organization standardized JavaScript?

  • Microsoft
  • Mozilla
  • Ecma International (correct)
  • Netscape

What tag is used to include JavaScript in an HTML document?

<p><code>&lt;script&gt;</code> (A)</p>
Signup and view all the answers

Where is the best place to include a <script> tag in an HTML document in order to ensure the page loads first?

<p>At the end of the <code>&lt;body&gt;</code> section (D)</p>
Signup and view all the answers

In JavaScript, what is a 'statement'?

<p>A single instruction that the JavaScript engine can execute (A)</p>
Signup and view all the answers

Which of the following is NOT a component that a JavaScript statement may contain?

<p>Variables (A)</p>
Signup and view all the answers

What does JavaScript ignore, allowing for better code readability?

<p>Extra spaces, tabs, and line breaks (B)</p>
Signup and view all the answers

Which keyword is used to create a variable in JavaScript?

<p><code>let</code> (A)</p>
Signup and view all the answers

What is a JavaScript function?

<p>A block of code designed to perform a particular task (A)</p>
Signup and view all the answers

Flashcards

What is JavaScript?

A scripting language embedded in web browsers that enables client-side scripting.

<script> tags

Tags used to include JavaScript code directly in an HTML document.

JavaScript components

Keywords, operators, values and expressions.

Keywords in JavaScript

Words that have special meaning in the JavaScript language.

Signup and view all the flashcards

Expressions

Units of code that result in a single value.

Signup and view all the flashcards

What is a variable?

A container in which data can be stored and retrieved.

Signup and view all the flashcards

Loosely Typed Variables

Variables that can store any data type without prior declaration.

Signup and view all the flashcards

let variables in JavaScript

Declared with the 'let' keyword, they can be reassigned new values.

Signup and view all the flashcards

Functions

A block of code designed to perform a task, it returns a single value.

Signup and view all the flashcards

Scope

Determines where a variable is accessible in a script.

Signup and view all the flashcards

Study Notes

  • These study notes cover the basics of JavaScript, including syntax, variables, functions and more.

What is JavaScript?

  • An object-based scripting language embedded in web browsers like Chrome, Edge, and Firefox.
  • Enables client-side scripting, which improves web page responsiveness.
  • Brendan Eich created JavaScript at Netscape in 1995; originally named LiveScript.
  • Was renamed to JavaScript to align with Java's popularity, but is not related to Java.
  • Before JavaScript, web pages relied on server-side scripts resulting in slower response times.
  • Allows for faster, interactive, and dynamic web experiences directly in the browser.

JavaScript Evolution & Key Features

  • Microsoft introduced JScript, which led to concerns about fragmentation.
  • In 1997, JavaScript was standardized as ECMAScript by Ecma International.
  • Despite being named ECMAScript, most developers still call it JavaScript.
  • Brendan Eich co-founded Mozilla and launched Firefox.
  • Language Basics include syntax, keywords, operators, and built-in objects.
  • Web Page Interaction involves manipulating the DOM for dynamic content.
  • Web Applications are used to create responsive web apps and handle JSON data.

Include Scripts

  • JavaScript code can be placed directly inside an HTML document using the <script> tag
  • Including javascript code with the script tag looks like this:
<script>
document.getElementById('message').innerText = 'Hello World!'
</script>
  • JavaScript can be placed in three locations inside an HTML document.
  • Not recommended to be placed in the <head> section unless it's a smaller script.
  • Can slow down page rendering if included inside the <body> section.
  • Best practice is to include inside the end of the <body> section to ensure the page loads first before running scripts.

External JavaScript

  • JavaScript code can be written in external plain text files with a .js file extension.
  • To include an external JavaScript file, tag with the src attribute is used: <script src="external_script.js"></script>
  • Reusability is made possible because the same script can be used across multiple web pages.
  • Better organization is established by keeping HTML clean and separating content from behavior.
  • Easier maintenance is enabled by updating the .js file updating all linked pages.
  • Do not include <script> tags inside the .js file, only write JavaScript code.

Console Output

  • JavaScript can dynamically write content into an HTML element using the innerText property alongside the element's specified id. document.getElementById('message').innerText = 'Hello World!';
  • JavaScript can display output using a pop-up alert using the alert() method to show specified content: window.alert('Hello World!');
  • For debugging, use the log() method of the console object to display the content specified within the console window: console.log('Hello World!');

Make Statements

  • JavaScript code is composed of a series of instructions called "statements".
  • Executed in top-to-bottom order as the browser's JavaScript engine processes the script.
  • Statements may contain keywords.
  • Statements may use operators, special characters that perform an operation.
  • Statements have values of text strings, numbers, boolean true or false, undefined, and null.
  • Expressions are units of code that produce a single value.

Statement Termination

  • In older versions, every statement had to end with a semicolon (;).
  • Semicolons are optional unless multiple statements are on the same line.
  • Some developers still prefer using semicolons for clarity.

Whitespace

  • Extra spaces, tabs, and line breaks are ignored.
  • Spacing improves readability.
  • Indent statements with a space bar, tab spacing may be treated differently in text editors.

Expressions vs. Statements

  • Expressions produce a value.
  • Statements perform an action.

JavaScript Statements & Syntax

  • JavaScript syntax is the rules that govern the JavaScript language.
  • Curly brackets {} are used to group statements inside function blocks.
  • Code blocks allow for reusable execution when required.
  • Indenting statements by two spaces leads to better readability.

Fixed Values (Literals)

  • Number literals include integer numbers or floating-point numbers.
  • String literals include text enclosed in single or double quotes.
  • Be consistent with string literals (use either single or double quotes).

Variable Values (Variables)

  • Variables store data within a script.
  • They can be created using the JavaScript let keyword
  • The variable can be assigned a value to store using the JavaScript = assignment operator

Expressions & Operators

  • An expression produces a single value by combining values and operators.
  • Expressions with variables look like this:
let total = 300;
let newTotal = (total - 200);
  • Operators used in expressions, such as: let finalValue = (100 + 50) * 2; // 300

Case Sensitivity

  • JavaScript is case-sensitive.
  • Variables total and Total are different.

Adding Comments

  • Comments help explain code for better readability and debugging.
  • Single-line comments begin with // and are useful for short explanations.
  • Multi-line comments are wrapped in /* and */ and are used for longer explanations or disabling blocks of code.
  • Comments should always be used to explain complex logic.

Store Values

  • Variables are containers, in a scripting language, store data that can be stored and retrieved.
  • Because of loose-typing, JavaScript variables are much easier to use

Data Types

Data type for Javascript values are as follows:

  • String: A string of text characters such as 'Hello World!'
  • Number: An int or float such as 3.142
  • Boolean: A true or false value
  • Object: A user-defined or built-in object
  • Function: A user defined function, a built-in function, or an object method
  • Symbol: A unique identifier
  • Null: Represents absolute nothing
  • Undefined: Represents a non-configured property

Loosely vs Strongly Typed Variables

  • Strongly typed variables in Java, C++, C# and other languages, must declare a type before use
  • In Javascript, variables can store ANY data without prior declaration

Declaring Variables

JavaScript Variables can be declared in 4 ways:

  1. Automatically
  2. Using var
  3. Using let
  4. Using const

Automatically

  • Variables are automatically declared when first used, considered bad practise
  • Example:
x = 5;
y = 6;
z = x + y;

Using var

  • The var keyword was used in all JavaScript code from 1995 to 2015.
  • The var keyword should only be used in code written for older browsers.
var x = 5;
var y = 6;
var z = x + y;

Using let

  • The let and const keywords were added to JavaScript in 2015.
  • Variables declared with let can be reassigned new values as the script proceeds
let x = 5;
let y = 6;
let z = x + y;
  • A let variable can be declared without a value and assigned later
let myNumber
myNumber = 5
let z = x + y;
  • Multiple variables may be declared on a single line too: let i,j,k; or let i = 10, j = 20

Using const

  • const is constant values and cannot be changed
  • Use const if the type should not be changed (Arrays and Objects)
const x = 5;
const y = 6;
const z = x + y;
  • Meaningful names for the variables will make the script easier to understand
  • Variable type for the value assigned are automatically set by JavaScript as well.
  • Variable type can still be changed, even after assignment.
  • Keyword to look for the current variable type is typeof.

Create Functions

  • Is a block of code designed to perform a particular task, and it returns a final single value.
  • A JavaScript function is executed when "something" invokes it (calls it).
  • Example
function myFunction(p1, p2) {
return p1 * p2;
}
  • JavaScript function starts with the keyword function

JavaScript Function Syntax

  • A Javascript starts with the keyword function then name then parenthesis
  • Function names can contain letters, digits, underscores, and dollar signs
  • Parenthesis has parameters like this: (parameter1, parameter2, ...)
  • Code to be executed is placed inside curly brackets {}:
  • Function arguments are values received by the function when it is invoked
  • Inside the function, arguments (the parameters) behave as local variables.

Function Invocation

Functions are invoked when:

  • when an event occurs
  • invoked (called) from javascript code
  • automatically.

Function Return

  • The function is stopped when JavaScript reaches a return statement.
  • Returns to execute the code after the invoking statement if the function was invoked from a statement.
  • The return value is "returned" back to the "caller" if functions often compute a return value.
  • Example:
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

Assign Functions

  • Assigning Functions to Variables in JavaScript is common, here is an example of assigning a name function:
function add(num1, num2) {
  return num1 + num2
}
let addition = add
console.log("Result:“, addition(100,200))

Anonymous Functions (Function Expressions)

  • Anonymous Functions, also known as Function Expressions are assigned without a name:
let anon = function (num1, num2) {
  return num1 + num2
}

Self-invoking functions

(function add(num1, num2) {
return num1 + num2
})()

Function Hoisting

  • JavaScript reads scripts in two sweeps
  • First Sweep: Finds function declarations and "hoists" them to the top.
  • Second Sweep: Executes the script.
  • This means function declarations can be called before they are defined.
  • For example
console.log("Volvo", add(100,200))
function add(num1, num2) {
  return num1 + num2
}
  • But Function Expressions Are not Hoisted!

Recognize Scope

  • Scope determines where a variable is accessible in a script.
  • JavaScript uses lexical scope, meaning the variable's environment decides its accessibility
  • There are usually 2 scopes: Global and Local

Global Scope

  • A global variable is declared outside of any function
  • It is accessible throughout the entire script
  • Potential Issue: Naming conflicts with external scripts.
  • Example:
let myName = ‘Ahmed';
function readName(a, b) {
  console.log(myName)
}

Local Scope

  • A local variable is declared inside a function
  • It only exists within that function and cannot be accessed outside
  • Example:
function readName(a, b) {
  let myName = 'Ahmed';
  console.log(myName)
}

Conversion Importance

  • JavaScript handles different data types differently and mixed data types can lead to unexpected results
  • Sometimes, converting a string or others types to numbers is important perform proper mathematical operations.

Example of Unexpected Behavior:

  • '42' + 8 will result in '428' (string concatenation, not addition).
  • Where '42' is a string, but 8 is a number.

Strings to Numbers Conversion

In JavaScript involves parseInt() and parseFloat().

  • parseInt() converts a string to an integer (whole number), ignores non-numeric characters like parseInt('42nd Street') results in 42
  • parseFloat() converts a string to a floating-point number, ignores non-numeric characters similar to parseInt

Non-Numeric Conversions

  • Javascript returns NaN (Not a Number) if conversion fails, like parseInt('Hello') will return NaN
  • isNaN(value) will return true if the value is not a number

Numbers to Strings

  • String() can be used
  • toString() function, for example:
let num = 42;
num.toString(); // Returns '42'

Arithmetic

Common arithmetic operators used in JavaScript are as follows:

  • + Addition of numbers / concatenation of strings
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus
  • ++ Increment
  • -- Decrement
  • ** Exponentiation

Assign Arithmetic

  • = basic assignment operator
  • += Addition
  • -= Subtraction
  • *= Multiplication
  • /= Division
  • %= Modulu
  • **= Exponentiation

Making Comparisons

In JavaScript, comparison Operators compare conditions between 2 values.

  • === and !== ensure strict equality for type and value
  • Relational Operators are >=, <=, <, and > to compare numerical values

Operator Comparison

  • === is equality
  • !== is inequality
  • > is greater than
  • < is less than
  • >= is greater than or equal to
  • <= is less than or equal to

Shorthand Operator

Ternary operator (?:)

  • Shorthand way to evaluate a condition in JavaScript, like the shown example: condition ? expression_if_true : expression_if_false

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

JavaScript Mastery Quiz
5 questions

JavaScript Mastery Quiz

PerfectNephrite4864 avatar
PerfectNephrite4864
JavaScript Fundamentals and Web Standards
24 questions
Introduction to JavaScript
40 questions
Use Quizgecko on...
Browser
Browser