본문 바로가기

JavaScript/SonarQube

[SonarQube] Consider using "forEach" instead of "map" as its return value is not being used here.

반응형

오늘 SonarQube에서 버그로  "Consider using "forEach" instead of "map" as its return value is not being used here." 이런 Warning이 발생되었다.

[SonarQube] Consider using "forEach" instead of "map" as its return value is not being used here.

상세 설명을 보면 "Return values from functions without side effects should not be ignored" 룰에 걸린다.

 

map 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환하는 메서드인데, 반환되는 값을 사용하지 않고 있기 때문에 발생하는 에러였다. 배열에 담긴 값을 순회하면서 읽어와 가공하여 다른 배열에 저장을 해주려고 한 로직이었는데 forEach 함수 대신 map 함수를 사용해서 발생되는 버그였다.

 

Compliant Solution

const array1 = [1, 4, 9, 16];

// 함수를 호출한 결과를 새로운 배열에 저장
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Noncompliant Code Example

const array1 = [1, 4, 9, 16];

// 반환 값이 사용되지 않음
array1.map(x => x * 2);

 

해결 방법

해결 방법은, 이렇게  반환 값을 사용하지 않고 단순히 배열의 값을꺼내서 루프를 돌리려면 map 함수 대신 forEach 함수를 사용하면 된다.

// map 대신 forEach 사용
array1.forEach(x => x * 2);

 

 

참고자료

반응형

'JavaScript > SonarQube' 카테고리의 다른 글

[SonarQube] Add an "alt" attribute to this image  (0) 2022.04.22
[SonarQube] Replace this <i> tag by <em>  (0) 2022.04.22