what is function in javascript

sunghoon·2024년 12월 27일
0

2.0 Glove Project

목록 보기
4/35
post-thumbnail

Function Declaration

  • the function keyword goes first
    then goes the name of the function
    then parameters between the parentheses
    finally the code of the function (body) between curly braces {...}
function name(parameter1, parameter2, ... parameterN) {
	// body
}
name () // executes function
  • main purposes is avoid code duplication

local variables

outer variables; global variables

  • it different local variables decalration that function modify outer variable.
  • local variable ignred outside block
// declare variable
let userName = 'John'

function showMessage () {
	let userName = "Bob"; // showMessage local variable
	alert("Hello" + userName);
}
alert(userName); // John
showMessage () // Hello Bob
alert(userName); // John
// modify variable
let userName = 'John';

function showMessage() {
  userName = "Bob";
  let message = 'Hello, '+ userName;
  alert(message);          
}

alert( userName ); // John
showMessage(); // Hello, Bob
alert( userName ); // Bob 

parameters

  • we can pass arbitrary data to function using parameters
function showMessage(from, test) {
	alert(from + ': ' + test);
}
showMessage('Ann', 'Hello');
showMessage('Ann', "what's up?");
function showMessage (from, text) {
	from = '*' + from + '*'
	alert(from + ': ' + text)
}
let from = "text"
showMessge(from, "Hello");
alert( from );
  • when a value is passed as a function parameter, it’s also called an argument.
  • we declare function listing their parameters, then call them passing arguments.

default value

it can use default if omitted value, using =

function showMessage(from, text = "no text given") {}
function changeText(from, text = anotherFunction()) {}
// it can use that complex expression like function

Alternative default parameters

// explicit check for undefined
function showMessage(from, text) {
	if (text === undefined) {
		text = 'no text given';
	}
	alert( from + ": " + text );
}

// Or using || operator
function showMessage(from, text) {
	text = text || 'no text given';
	alert( from + ": " + text );
}
// the nullish coalescing operator
function showCount(count) {
	//if count is undefined or null, show "unknown"
	alert(count ?? "unknown");
}

showCount(0); // 0
showCount(null); // unknown
showCount(); // unknown

Returning a value

function sum(a, b) {
	return a + b;
}
let result = sum(1, 2);
alert( result ); // 3
  • The directive return can be in any place of the function. When the excution reaches it, the function stop, and the value is returned to the calling code (assigned to result above)
    There may be many occurrences of return in a single function. For instance:
function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
  return confirm('Do you have permission from your parents?');
  }
}
let age = prompt('How old are you?', 18);

if ( checkAge(age) ) {
  alert ( 'Access granted' );
} else {
  alert( 'Access denied' );
}
  • it is possible to use return without a value. That causes the function to exit immediately.
function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
  return confirm('Do you have permission from your parents?');
  }
}
let age = prompt('How old are you?', 18);
checkAge(age);
function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
  return confirm('Do you have permission from your parents?');
  }
}

function showMovie(age) {
  if ( !checkAge(age) ) {
    return; // exit immediately
  }
  alert( "Showing you the movie" );
}

let age = prompt('How old are you?', 18);
showMovie(age)

//In the code above, if checkAge(age) return false, then showMovie won't proceed to the alert
  • A function with an empty return or without it return undefined
    If a function does not return a value, it is the same as if it returns undefined:
function doNothing() { /* empty */}
  • An empty return is also the same as return undefined:
function doNothing() {
	return;
}
alert( doNothing() === undefined ); // true
  • Never add a newline between return and the value
    for a long expression in return, it might be tempting to put it on a separate line, like this:
return
	("test...")
  • we should start it at the same line as return.
    Or at least put the opening parentheses there as follows:
return (
	some + long + expression
	+ or + 
	whatever * f(a) + f(b)
)
  • And it will work just as we expect it to.

functions name == comments

function showPrimes(n) {
	nextPrime: for (let i = 2; i < n; i++) {
		for (let j = 2; j < i; j++) {
			if (i % j == 0) continue nextPrime;
		}
		
		alert(i); // a prime
	}
}

The second variant uses an additional function isPrime(n)to test to primality:

let num = +prompt("type number")
    
function showPrimes(n) {
  for (let i = 2; i < n; i++) {
    if (!isPrime(i)) continue;
    
    alert(i);
  }      
}

function isPrime(n) {
  for (let i = 2; i < n; i++) {
    if ( n % i == 0 ) return false;
  }
  return true;
}

showPrimes(num);
  • The second variant is easier to understand
    refer to such code as self-describing

Tasks

  • Is “else” required?
function checkAge(age) {
  if (age > 18) {
    return true; // quit so don't need else
  }
  return confirm('Did parents allow you?');
}
  • rewrite the function using ‘?’ or ‘||’ instead ‘if’
function checkAge(age) {
   return (age > 18) || confirm('check')
}
let age = prompt("How old you?")
checkAge(age)
  • function min(a, b)
  • Function pow(x,n)
profile
프라다 신은 빈지노와 쿠페를 타는 꿈을 꿨다.

0개의 댓글