Skip to content

Instantly share code, notes, and snippets.

@rndomhack
Last active May 10, 2016 11:31
Show Gist options
  • Save rndomhack/41d9fa7d3f1b6605a132da0b4a829c5d to your computer and use it in GitHub Desktop.
Save rndomhack/41d9fa7d3f1b6605a132da0b4a829c5d to your computer and use it in GitHub Desktop.
JavaScript CheatSheet

JavaScript CheatSheet

コメント

// comment

/*
    comments
*/

/*
    /*
        nested comments
    */
*/  // SyntaxError

変数

基本

var foo;
foo = "foo";

let bar = 0;
bar = "bar";        // OK

const baz = "baz";
baz = "foobar";     // TypeError

巻き上げ

console.log(foo);   // undefined
var foo = "foo";
console.log(foo);   // "foo"

console.log(bar);   // ReferenceError
let bar = "bar";
console.log(bar);   // "bar"

console.log(baz);   // ReferenceError
const baz = "baz";
console.log(baz);   // "baz"

スコープ

(function() {
    // function scope
    {
        // block scope
        var foo = "foo";
        let bar = "bar";
        const baz = "baz";
    }

    console.log(foo);   // "foo"
    console.log(bar);   // ReferenceError
    console.log(baz);   // ReferenceError
})();

console.log(foo);   // ReferenceError

基本

null;               // null
undefined;          // undefiend
true;               // Boolean
1024;               // Number
"string";           // String
Symbol("symbol");   // Symbol
{ foo: "bar" };     // Object

リテラル

let array = [false, , 42];
array[0];                       // false
array[1];                       // undefined

0xFFFF + 0o1234 - 0b1010;       // 65535(hex) + 668(oct) - 10(bin) = 66193

let string = 'bar';
"foo\n" + string + "\nbaz";     // "foo\nbar\nbaz"
`foo
${string}
baz`;                           // "foo\nbar\nbaz"

let object = {
    foo: "foo",
    0: "0"
};
object.foo;                     // "foo"
object[foo];                    // ReferenceError
object["foo"];                  // "foo"
object.0;                       // SyntaxError
object[0];                      // "0"
object["0"];                    // "0"

キャスト

"" + 123                // "123"
(123).toString()        // "123"
+"456"                  // 456
parseInt("456", 10)     // 456

評価

1 === 1;            // true
1 === 0;            // false
1 !== 1;            // false

1 === "1";          // false
1 == "1";           // true

0;                  // false
"";                 // false
undefined;          // false
null;               // false
NaN;                // false

"foo";              // true
{};                 // true
new Boolean(false); // true

null === null       // true
NaN === NaN         // false

0 == false          // true
1 == true           // true
"" == false         // true

演算子

算術演算子

let x = 5; y = 3, z = "1";

x + y;      // 5 + 3 = 8
x - y;      // 5 - 3 = 2
x * y;      // 5 * 3 = 15
x / y;      // 5 / 3 = 1.666...
x % y;      // 5 mod 3 = 2
x ** y;     // 5 ^ 3 = 125 (Math.pow(5, 3))

-x;         // -5
+z;         // 1
x++;        // x = x + 1
x--;        // x = x - 1

ビット演算子

let x = 5; y = 3, z = -1;

x & y;      // 101 and 011 = 001
x | y;      // 101 or 011 = 111
x ^ y;      // 101 xor 011 = 110
~x;         // not 101 = 111111...010
x << y;     // 101 << 3 = 101000
x >> y;     // 101 >> 3 = 0
z >>> y;    // 111111...111 >>> 3 = 000111...111

論理演算子

true && true;           // true
true && false;          // false
false && true;          // false
false && false;         // false
"first" && "second";    // "second"
"" && "second";         // ""
"first" && "";          // ""
"" && undefined;        // ""

true || true;           // true
true || false;          // true
false || true;          // true
false || false;         // false
"first" || "second";    // "first"
"" || "second";         // "second"
"first" || "";          // "first"
"" || undefined;        // undefined

!true;                  // false
!false;                 // true
!"string";              // false
!"";                    // true
!!{};                   // true

代入演算子

let x = 5; y = 3;

x = y;
x += y;     // x = x + y
x -= y;     // x = x - y
x *= y;     // x = x * y
x /= y;     // x = x / y
x %= y;     // x = x % y
x **= y;    // x = x ** y
x &= y;     // x = x & y
x |= y;     // x = x | y
x ^= y;     // x = x ^ y
x <<= y;    // x = x << y
x >>= y;    // x = x >> y
x >>>= y;   // x = x >>> y

文字列演算子

let string = "", abc = "abc", def = "def";

abc + def;      // "abcdef"

string += def;
string += abc;
string;         // "defabc"

三項演算子

true ? "true" : "false";    // "true"

コンマ演算子

1, 2, 3, 4, 5;          // 5

単項演算子

delete

undeclared = "undeclared";
var declared = "declared";
var object = {
    foo: "1",
    bar: "2"
};

delete undeclared;          // true
console.log(undeclared);    // ReferenceError

delete declared;            // false
console.log(declared);      // "declared"

delete object.foo;          // true
console.log(object.foo);    // undefined

delete Math.PI;             // false
console.log(Math.PI);       // 3.141592653589793

typeof

typeof true;                // "boolean"
typeof 1024;                // "number"
typeof "string";            // "string"
typeof Symbol("symbol");    // "symbol"
typeof {};                  // "object"
typeof function() {};       // "function"
typeof undefined;           // "undefined"

typeof undefVar;            // "undefined"
typeof new Date();          // "object"
typeof null;                // "object"

void

void 0 === undefined;   // true

関係演算子

in

let object = {
    foo: "1",
    bar: "2"
};

"foo" in object;        // true
"baz" in object;        // false

instanceof

let instance = new Number(42);
let literal = 42;

instance instanceof Number;     // true
instance instanceof Date;       // false

literal instanceof Number;      // false

制御文

if 文

let number = 1;

if (number === 0) {
    console.log("number is zero");
} else if (number === 1) {
    console.log("number is one");
} else {
    console.log(`number is ${number}`);
}

// result: "number is one"

switch 文

let number = 1

switch (number) {
    case "1":
        console.log("number is \"1\"");
        break;

    case 1:
        console.log("number is 1");
        break;

    default:
        console.log(`number is ${number}`);
}

// result: "foo is 1"

throw 文

throw new Error("Throw error instance");
throw new TypeError("Throw type error instance");
throw 1;
throw "Throw string";
throw { message: "Throw object" };

try ... catch 文

try {
    throw new Error("Error occurred!");
} catch (err) {
    err.name;               // "Error"
    err.message;            // "Error occurred!"
    err.stack;              // "Error: Error occurred!\n    at..."
} finally {
    console.log("finally");
}

for 文

for (let i = 0; i < 10; i++) {
    console.log(`i is ${i}`);
}

// result: "i is 0" "i is 1" ... "i is 9"

for ... in 文

var object = {
    foo: "1",
    bar: "2",
    baz: "3"
};

for (key in object) {
    console.log(`${key} is ${object[key]}`);
}

// result: "foo is 1" "bar is 2" "baz is 3"

for ... of 文

var array = ["foo", "bar", "baz"];
array.foobar = "foobar";

for (key in array) {
    console.log(array[key]);
}

// result: "foo" "bar" "baz" "foobar"

for (value of array) {
    console.log(value);
}

// result: "foo" "bar" "baz"

do ... while 文

let string = "";

do {
    string += "a";
} while (string !== "aaa");

console.log(string);

// result: "aaa"

while 文

let number = 0;

while (number < 10) {
    number += 2;
}

console.log(number);

// result: 10

break 文, continue 文, label文

let foo = 0, bar = 0;

loop:
while (true) {
    foo += 5;

    if (foo % 10 === 0) continue;

    while (true) {
        bar++;

        if (bar > 9) {
            bar = 0;
            break;
        } else if (foo + bar > 123) {
            break loop;
        }
    }
}

console.log(foo, bar);

// result: 115 9

関数

基本

typeof func;            // "function"
func(1, 2);             // 3

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

func(3, 4);             // 7

関数式

typeof func;            // "undefined"
func(1, 2);             // TypeError

var func = function (x, y) {
    return x - y;
}

func(3, 4);             // -1

アロー関数

var func = (x, y) => {
    return x * y;
}

func(1, 2);             // 2

再帰

function recursive(x) {
    if (x <= 1) return x;

    return x * recursive(x - 1);
}

recursive(5);           // 5 * 4 * 3 * 2 * 1 = 120

クロージャ

function closure(x) {
    return function (y) {
        return x * y;
    }
}

let func = closure(5);

func(1);                // 5 * 1 = 5
func(5);                // 5 * 5 = 25

仮引数

function func(x = 1) {
    return x;
}

function func2(...args) {
    return args;
}

func();                 // 1
func(5);                // 5
func2();                // []
func2(1, 2, 3);         // [1, 2, 3]

オブジェクト

基本

let foo = {};
let bar = {};
let baz = foo;

foo === bar;            // false
foo === baz;            // true

let nana = {
    name: "nana",
    age: 15,
    sex: "female",
    get type() {
        return "human";
    },
    say() {
        return `Hello! I\'m ${this.name}!`;
    }
};

nana.name;              // "nana"
nana.age;               // 15
nana.sex;               // "female"
nana.type;              // "human"
nana.say();             // "Hello! I'm nana!"

nana.type = "animal";
nana.type;              // "human"

Object.create メソッド

let Human = {
    name: "",
    age: 0,
    sex: "female",
    get type() {
        return "human";
    },
    say() {
        return `Hello! I\'m ${this.name}!`;
    }
};

let nana = Object.create(Human);
/*
let nana = {};
nana.__proto__ = Human;
*/
nana.name = "nana";
nana.age = 15;
nana.speak = function() {
    return "I love sushi!";
};

nana.name;          // "nana"
nana.age;           // 15
nana.sex;           // "female"
nana.type;          // "human"
nana.say();         // "Hello! I'm nana!"
nana.speak();       // "I love sushi!"

Human.name;         // ""

コンストラクタ

function Cat(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

Object.defineProperty(Cat.prototype, "type", {
    get: function() {
        return "cat";
    }
});

Cat.prototype.meow = function() {
    return `Meow! (I\'m ${this.name})`;
}

let tama = new Cat("tama", 3, "male");

tama.name;          // "tama"
tama.age;           // 3
tama.sex;           // "male"
tama.type;          // "cat"
tama.meow();        // "Meow! (I'm tama)"

tama.__proto__ === Cat.prototype;   // true

継承

// Animal
function Animal(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

Object.defineProperty(Animal.prototype, "type", {
    get: function() {
        return "animal";
    }
});

// Cat
function Cat() {
    Animal.apply(this, arguments);
}

Cat.prototype = Object.create(Animal.prototype);

Object.defineProperty(Cat.prototype, "type", {
    get: function() {
        return "cat";
    }
});

Cat.prototype.meow = function() {
    return `Meow! (I\'m ${this.name})`;
}

let pochi = new Animal("pochi", 5, "female");

pochi.name;         // "pochi"
pochi.age;          // 5
pochi.sex;          // "female"
pochi.type;         // "animal"
pochi.meow();       // TypeError

let tama = new Cat("tama", 3, "male");

tama.name;          // "tama"
tama.age;           // 3
tama.sex;           // "male"
tama.type;          // "cat"
tama.meow();        // "Meow! (I'm tama)"

class 構文

"use strict";

// Animal
class Animal {
    constructor(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    get type() {
        return "animal";
    }
}

// Cat
class Cat extends Animal {
    constructor(name, age, sex) {
        super(name, age, sex);
    }

    get type() {
        return "cat";
    }

    meow() {
        return `Meow! (I\'m ${this.name})`;
    }
}

let pochi = new Animal("pochi", 5, "female");

pochi.name;         // "pochi"
pochi.age;          // 5
pochi.sex;          // "female"
pochi.type;         // "animal"
pochi.meow();       // TypeError

let tama = new Cat("tama", 3, "male");

tama.name;          // "tama"
tama.age;           // 3
tama.sex;           // "male"
tama.type;          // "cat"
tama.meow();        // "Meow! (I'm tama)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment