return / break / continue

choi seung-iยท2022๋…„ 4์›” 15์ผ
0

JS๋กœ๊ทธ

๋ชฉ๋ก ๋ณด๊ธฐ
10/14
post-thumbnail

๐Ÿ”ฝย  return

  • ๋ฐ˜๋ณต๋ฌธ์„ ์ข…๋ฃŒ ์‹œํ‚ค๊ธฐ๋„ ํ•˜์ง€๋งŒ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ํ•จ์ˆ˜ ์ž์ฒด๋ฅผ ์ข…๋ฃŒ

  • ํ•จ์ˆ˜์—์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒ
    โ‡’ ํ•จ์ˆ˜๋Š” return์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ํ•ญ์ƒ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•จ (๊ธฐ๋ณธ๊ฐ’์€ undefined)

    const number = () => {
        for (let i = 0; i < 10; i++ ) {
            if(i===5) {
                return i;
            }
            console.log(i)
        }
    }
    
    console.log('์ข…๋ฃŒ')
    number()
    
    // 0 , 1 , 2 , 3 , 4 , ์ข…๋ฃŒ



๐Ÿ”ฝย break

  • ๋ฐ˜๋ณต๋ฌธ์„ ๋” ์ด์ƒ ์ง„ํ–‰ํ•˜์ง€ ์•Š์•„๋„ ๋  ๋•Œ ๋ถˆํ•„์š”ํ•œ ๋ฐ˜๋ณต์„ ํšŒํ”ผํ•  ์ˆ˜ ์žˆ์–ด์„œ ์œ ์šฉ

  • ๋ ˆ์ด๋ธ”๋ฌธ(์‹๋ณ„์ž๊ฐ€ ๋ถ™์€ ๋ฌธ), ๋ฐ˜๋ณต๋ฌธ(for, for...in, for...of, while, do...while), switch๋ฌธ์˜ ์ฝ”๋“œ ๋ธ”๋ก ํƒˆ์ถœ
    => ๊ทธ ์™ธ์— break๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด SyntaxError(๋ฌธ๋ฒ• ์—๋Ÿฌ) ๋ฐœ์ƒ

    if(true) {
        break; //SyntaxError
    }

๋ ˆ์ด๋ธ”๋ฌธ ?

  • ์ค‘์ฒฉ๋œ for๋ฌธ ์™ธ๋ถ€๋กœ ํƒˆ์ถœํ•  ๋•Œ ์œ ์šฉ ( ๊ทธ ์™ธ๋Š” ๊ถŒ์žฅX)

    foo: {
        console.log(1);
        break foo;  //foo ๋ ˆ์ด๋ธ” ๋ธ”๋ก๋ฌธ์„ ํƒˆ์ถœ.
        console.log(2);
    }
    outer : for (lse i = 0; i < 3; i++) {
        for (let i = 0; i < 3; i++) {
            if (i + j === 3) break outer;
        }
    }

    ์˜ˆ) ๋ฌธ์ž์—ด์—์„œ ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ์ฒ˜์Œ ์žˆ๋Š” ์ธ๋ฑ์Šค ์ฐพ๊ธฐ

    const string = 'Hello World'
    let index;
    
    for(let i = 0; i < string.length; i++) {
        if(string[i] === 'l') {
            index = i;
            break;
        }
    }
    
    // 2



๐Ÿ”ฝย continue

  • ํŠน์ • ์กฐ๊ฑด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์กฐ๊ฑด์— ๋งŒ์กฑํ•˜๋ฉด ๋ช…๋ น์„ ๊ฑด๋„ˆ๋›ฐ๊ณ  ๋‹ค์Œ์œผ๋กœ ๋„˜์–ด๊ฐ

  • ๋ฐ˜๋ณต๋ฌธ์˜ ์ฝ”๋“œ ๋ธ”๋ก ์‹คํ–‰์„ ํ˜„ ์ง€์ ์—์„œ ์ค‘๋‹จํ•˜๊ณ  ๋ฐ˜๋ณต๋ฌธ์˜ ์ฆ๊ฐ์‹์œผ๋กœ ์‹คํ–‰ ํ๋ฆ„์„ ์ด๋™

    ์˜ˆ) ๋ฌธ์ž์—ด์—์„œ ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ๋ช‡๊ฐœ๋‚˜ ์žˆ๋Š”์ง€ ์นด์šดํŠธ

    const string = 'Hello World'
    let index;
    
    for(let i = 0; i < string.length; i++) {
        if(string[i] !== 'l') continue;
        count++ //๋งŒ์•ฝ ๋ฌธ์ž์—ด์— l์ด ์—†์œผ๋ฉด ์ด ์ค„์ด ์‹คํ–‰๋˜์ง€ ์•Š๊ณ  i++๋กœ ์ง„ํ–‰
        }
    }
    
    // 3
  • continue๋ฌธ์„ ์•ˆ์“ธ์ˆ˜๋„์žˆ์ง€๋งŒ,
    ์‚ฌ์šฉํ–ˆ์„ ๊ฒฝ์šฐ ์‹คํ–‰์ฝ”๋“œ๊ฐ€ ๋งŽ๋‹ค๋ฉด if๋ฌธ ๋ฐ–์—์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ์ด ์ข‹์Œ

    ```jsx
    for (let i = 0; i < string.length; i++) {
    	if(string[i] === search) {
    		count++;
    		//์ฝ”๋“œ
    		//์ฝ”๋“œ
    		//์ฝ”๋“œ
    	}
    }
    ```
    
    ```jsx
    ๐ŸŒŸ
    for (let i = 0; i < string.length; i++) {
    	if(string[i] !== search) continue;
    
    	count++;
    	//์ฝ”๋“œ
    	//์ฝ”๋“œ
    	//์ฝ”๋“œ
    }
    ```


๊ณต๋ถ€ํ•˜๋ฉฐ ์ •๋ฆฌ&๊ธฐ๋กํ•˜๋Š” ._. ์”…๋กœ๊ทธ

profile
Front-end

0๊ฐœ์˜ ๋Œ“๊ธ€