Basics of JavaScript Syntax

Sungju Kim·2024년 7월 19일

Sparta_Coding_Camp_TIL

목록 보기
2/53

let

'let' can be declared globally, but its access is limited to the block in which it is declared.

let my_var = 'hello world'

var

'var' can be declared and accessed globally.

let vs. var

The second console.log will not be printed because 'hello' is only accessible to the block in which it is declared.

function example() {
    if (true) {
        let hello = "hello world";
        console.log(hello); // Accessible here
    }
    console.log(hello);
}

example();

list

lists are indexable

let my_list = [1, 3, 4]
console.log(my_list[0])

output

1

dictionary

let my_info = {'name':'Sungju', 'age':23, 'nationality': 'Korean'}
console.log(my_info['name'])

output

Sungju

if-condition

Syntax is similar to C++

let age = 19
if (age<18) {
	console.log('underaged')
}
else {
	console.log('underaged')
}

for-loop***

Syntax is unique to python or C/C++

let fruits = ['apple','pear','grapes','lemon', 'orange']
fruits.forEach((a) => {
	console.log(a)
}) 

function

function hey() {
	alert('hello world!')
}

let's try using this in a HTML element

<button onclick="hey()" type="button" 
class="btn btn-outline-light">Say Hi</button>

Another example

function getInteger() {
    return 42; // Returns the integer 42
}

jquery

  • Javascript library

JS Function in HTML script

'#title' refers to the id attribute of an element. It is an easy way to refer to it when writing a function in

<script>
		function hey() {
			if ($('#title').text() === 'Kingdom')
            {
				$('#title').text('킹덤');
			}
			else
            {
				$('#title').text('Kingdom');
			}
		}
</script>

The HTML tag we are modifying with the function should have the id 'title' in order for us to access it in the script.

<h1 id="title" class="display-5 fw-bold">킹덤</h1>

Modifying HTML tags using JS functions

function checkResult() {
		let fruits = ['사과','배','감','귤','수박']
		$('#q1').empty(); // empty out the fruites currently on display
		
		fruits.forEach(a => {
			let temp = `<p>${a}</p>`
			$('#q1').append(temp);
		})
    }

Dictionary

// here people is a list of dictionaries.
function checkResult() {
		let people = [
			{ 'name': '서영', 'age': 24 },
			{ 'name': '현아', 'age': 30 },
			{ 'name': '영환', 'age': 12 },
			{ 'name': '서연', 'age': 15 },
			{ 'name': '지용', 'age': 18 },
			{ 'name': '예지', 'age': 36 }
		]
		$('#q2').empty()
		
		people.forEach((person) => {
			let temp = `<p>${person['name']}는 ${person['age']}살입니다.</p>`
			$('#q2').append(temp)
		})
	}
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글