JavaScript基本構文

変数とデータ型

変数の宣言方法

JavaScriptでは、varletconstの3つのキーワードで変数を宣言できます。

  • var: 関数スコープを持つ古い宣言方法
  • let: ブロックスコープを持つES6以降の宣言方法
  • const: 変更不可の定数を宣言するES6以降の方法
// varで宣言
var userName = 'Taro';

// letで宣言
let userAge = 20;

// constで宣言
const PI = 3.1415;

データ型

プリミティブ型

  • string: 文字列型
  • number: 数値型
  • bigint: 大きな整数型(ES2020)
  • boolean: 真偽値型
  • undefined: 未定義値
  • null: 空値
  • symbol: 一意な値(ES6)
let text = 'Hello'; // string
let count = 100; // number
let bigNum = BigInt('9007199254740991'); // bigint
let isActive = true; // boolean
let value; // undefined
let empty = null; // null
let id = Symbol('id'); // symbol

オブジェクト型

  • Object: オブジェクト
  • Array: 配列
  • Function: 関数
  • Date: 日付
  • RegExp: 正規表現
// オブジェクト
let person = {
  name: 'Hanako',
  age: 25
};

// 配列
let colors = ['red', 'green', 'blue'];

// 関数
function sayHello(name) {
  console.log(`Hello, ${name}`);
}

// 日付
let now = new Date();

// 正規表現
let pattern = /^[a-z]+$/;

演算子と制御構文

算術演算子

let a = 8;
let b = 3;
console.log(a + b); // 11
console.log(a - b); // 5
console.log(a * b); // 24
console.log(a / b); // 2.666...
console.log(a % b); // 2

比較演算子

let x = 5;
let y = '5';
console.log(x == y); // true(型変換あり)
console.log(x === y); // false(型変換なし)

条件分岐

let score = 75;
if (score >= 60) {
  console.log('合格');
} else {
  console.log('不合格');
}

let fruit = 'apple';
switch (fruit) {
  case 'apple':
    console.log('りんご');
    break;
  case 'orange':
    console.log('みかん');
    break;
  default:
    console.log('その他');
}

繰り返し処理

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

let counter = 0;
while (counter < 3) {
  console.log(counter);
  counter++;
}

let index = 0;
do {
  console.log(index);
  index++;
} while (index < 5);

関数と配列

関数の定義と呼び出し

function add(x, y) {
  return x + y;
}

const multiply = function(x, y) {
  return x * y;
};

console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20

スプレッド構文

function sumAll(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sumAll(1, 2, 3, 4)); // 10

配列操作

// 配列の作成
let arr1 = [1, 2, 3];
let arr2 = new Array(5); // 長さ5の空配列

// 要素の追加・削除
arr1.push(4);
arr1.unshift(0);
arr1.pop();
arr1.shift();

// 配列の操作
arr1.sort((a, b) => a - b);
arr1.reverse();
let newArr = arr1.concat([5, 6]);

// 配列の走査
for (let i = 0; i < arr1.length; i++) {
  console.log(arr1[i]);
}

arr1.forEach((item) => {
  console.log(item);
});

タグ: javascript ES6 変数 関数 配列

7月24日 01:19 投稿