Основы JavaScript

Содержание
Введение
Цикл forEach
Похожие статьи

Ctrl + Shift + I or F12 to open the Dev Tools

alert("Hello World!")

// is a comment

2**4 is 16

10/2
5

15 % 14
1
6%2
0

clear() - to clear the console //STRINGS "Django is cool"
"Django"+" is super cool"
"Django is super cool"

"django".length
6

"x x".length
3

"hello \n start a new line"
"hello
start a new line"

"hello \t give me a tab"
"hello    give me a tab"

"hello \"quotes\" "
"hello "quotes" "

"hello \" jelly"
"hello " jelly"

"hello"[0]
"h"

Strings

"hello"[4]
"o"

"look at the dog"[12]
"d"

Variables

//VARIABLES

// let varName = value;

let bankAccount = 100;

bankAccount
100

let deposit = 50;

let total = bankAccount + deposit

total
150

let greeting = "Welcome back: ";

let name = "Andrei";

alert(greeting+name);

let myVariable
undefined

let bonus = null;
undefined

Some methods

alert("Hey!")
undefined

console.log("Hey I am in the console");
Hey I am in the console

prompt("Enter something")
"I type some text here"

let age = prompt("Enter your age: ")
undefined

age
"111"

Connecting JavaScript to HTML

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

Inside the script file:

alert("Welcome to www.eth1.ru");

Ibs to kg

Скрипт

let weightInIbs = prompt("What is the weight in pounds?"); let weightInKg; weightInKg = weightInIbs * 0.454; alert("It is "+weightInKg+" kg"); console.log("Conversion completed"); Проверить здесь

Operators

true
true

false
false

3>2
true

2>3
false

2>2
false

2 >= 2
true

1 <= 3
true

2 == 2
true

"www.heihei.ru" == "www.heihei.ru"
true

"2" == 2
true

"2" === 2
false

5 !== "5"
true

5 != "5"
false

true == 1;
true

true === 1;
false

false == 0
true

false === 0
false

null == undefined
true

null === undefined
false

NaN == Nan
false

Logical operators

1 === 1
true

2 === 2
true


//AND
undefined

1 === 1 && 2 === 2
true

1===1 && 2===2 && 1===2
false

//OR
undefined

1 === 2 || 1 === 1
true

//NOT
undefined

(1===1)
true

!(1===1)
false

!!(1===1)
true

!!!!!(1===1)
false

Control Flow

IF statement

if (condition){
//Execute some Code
}
else if (condition two){
//Execute some other Code
}
else{
//Execute some backup Code
}

Example 1

let id == 100; console.log(id === 100 ? 'CORRECT' : 'INCORRECT')

Example 1

let hot = false
let temp = 60


if (temp>80){
hot=true
}
console.log(hot)

Example 2

let hot = false
let temp = 100


if (temp>80){
console.log("Hot Outside!");
}
else if (temp <=89 && temp >=50) {
console.log(Average temp Outside");

}
else if (temp < 50 && temp >=32) {
console.log("Its pretty cold out!");
}
else {
console.log("Its very cold out!"}

While Loop

while (condition){
// Execute some code while
// this condition is true
}

Example 1

let x = 0; while (x < 5) { console.log("x is currently: " + x); console.log("x is still less than 5, adding 1 to x"); x = x + 1; }

Example 2

let x = 0; while (x < 5) { console.log("x is currently: " + x); if (x === 3) { console.log("X IS EQUAL TO THREE!"); break; } console.log("x is still less than 5, adding 1 to x"); x = x + 1; }

Example 3

// Write a while Loop that prints out // only the even numbers from 1 to 10 let num = 1; while (num < 11) { if (num % 2 === 0) { console.log(num); } num = num + 1; }

For Loops

For Loops allow you to continually execute code a specific number of times.

Javascript has three types of For Loops:

For - loops throught a number of times
For/In - loops through a JS object
For/of - used with arrays

A quick note, previously we used the notation: num = num +1
num += 1
num++
These are all the same

For Loop Syntaxis

for (statement1; statement2; statement3) { // Execute some code } Statement 1 is executed before the loop(the code block) starts. for(let i = 0; statement2; statement3) { // Execute some code } Statement 2 defines the condition for running the loop for (let i = 0; i < 5; statement3) { // Execute some code }

Example 1

for (let i = 0; i < 5; i++) { console.log("Number is " + i); }

Example 2

let word = "ABCDEFGHIJK" for (let i = 0; i < word.length; i++) { console.log(word[i]); }

Example 3

let word = "ABABABABAB" for (let i = 0; i < word.length; i = i + 2) { console.log(word[i]); }

Изображение баннера

Spy Test

let LastName = prompt("Hello, please enter our Last Name"); console.log(LastName); let FirstName = prompt("Hello, please enter our First Name"); console.log(FirstName); let Age = prompt("Hello, please enter your Age"); console.log(Age); let Height = prompt("How tall are you?"); console.log(Height); let Pet = prompt("What is your pets name"); console.log(Pet); alert("Thank you so much for the information."); let nameCond = null let ageCond = null let heightCond = null let petCond = null if (LastName[0] === FirstName[0]) { nameCond = true; } else { nameCond = false; } if (Age < 30 && Age > 20) { ageCond = true; } else { ageCond = false; } if (Height > 170) { heightCond = true; } else { heightCond = false; } if (Pet[Pet.length - 1] === "y") { petCond = true; } else { petCond = false; } if (nameCond && ageCond && heightCond && petCond) { // My secret message console.log("Welcome Comrade! Youve passed the Spy Test") }else{ console.log("Sorry, nothing to see here.") }

Ошибки

Uncaught TypeError: Cannot read property 'textContent' of undefined

Такая ошибка может появиться по нескольким причинам. Самая простая - Вы подключили скрипт раньше чем на странице загрузились элементы, которые Вы выделяете.

Решение - вставить скрипт в конец страницы.

Uncaught SyntaxError: Unexpected token '<'

Скорее всего неправильно подключен скрипт. Путь указан, а самого скрипта там нет. Генерируется страница с ошибкой

В консоли браузера скорее всего есть упоминание страницы обработчика 404 ошибки

Например: VM1515 404.php

Цикл forEach

const array1 = ['a', 'b', 'c']; array1.forEach((element) => console.log(element));

a b c

Похожие статьи
JavaScript
Функции
typeof(): Определить тип переменной
Массивы
Сортировка массива
Скролл вверх и вниз
Определить ширину экрана
Mocha Framework
Запросы к REST API на JS
TicTacToe
Ошибки
Изображение баннера

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: